webman 如何输出二进制图片流?

问题描述

做一个文字生成图片的功能,客户端需要接收是二进制图片,webman如何返回二进制图片?

488 3 0
3个回答

@walkor 请求大佬百忙之中解答一下,万分感谢!!!!

  • 我家门前没大树 2023-09-14

    // 输出图像
    ob_start();
    imagepng($img);
    $content = ob_get_contents();
    imagedestroy($img);
    ob_end_clean();
    return response($content);

admin

我认为 明明文档里很[明显]有的,是对 写文档的作者的一种不尊重。

https://www.workerman.net/doc/webman/response.html

返回文件流

<?php
namespace app\controller;

use support\Request;

class FooController
{
    public function hello(Request $request)
    {
        return response()->file(public_path() . '/favicon.ico');
    }
}

webman支持发送超大文件
对于大文件(超过2M),webman不会将整个文件一次性读入内存,而是在合适的时机分段读取文件并发送
webman会根据客户端接收速度来优化文件读取发送速度,保证最快速发送文件的同时将内存占用减少到最低
数据发送是非阻塞的,不会影响其它请求处理
file方法会自动添加if-modified-since头并在下一个请求时检测if-modified-since头,如果文件未修改则直接返回304以便节省带宽
发送的文件会自动使用合适的Content-Type头发送给浏览器
如果文件不存在,会自动转为404响应

下载文件

<?php
namespace app\controller;

use support\Request;

class FooController
{
    public function hello(Request $request)
    {
        return response()->download(public_path() . '/favicon.ico', '可选的文件名.ico');
    }
}

download方法与file方法的区别是download方法一般用于下载并保存文件,并且可以设置下载的文件名。download方法不会检查if-modified-since头。其它与file方法行为一致。

获取输出
有些类库是将文件内容直接打印到标准输出的,也就是数据会打印在命令行终端里,并不会发送给浏览器,这时候我们需要通过ob_start(); ob_get_clean(); 将数据捕获到一个变量中,再将数据发送给浏览器,例如:

<?php

namespace app\controller;

use support\Request;

class ImageController
{
    public function get(Request $request)
    {
        // 创建图像
        $im = imagecreatetruecolor(120, 20);
        $text_color = imagecolorallocate($im, 233, 14, 91);
        imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

        // 开始获取输出
        ob_start();
        // 输出图像
        imagejpeg($im);
        // 获得图像内容
        $image = ob_get_clean();

        // 发送图像
        return response($image)->header('Content-Type', 'image/jpeg');
    }
}
  • 暂无评论
xiaoming

我认为 明明文档里很[明显]有的,是对 写文档的作者的一种不尊重。

  • 暂无评论
🔝