首页 > 解决方案 > 强制下载图像作为响应流明 + 干预图像

问题描述

我在我的 Lumen 项目中使用干预图像,一切正常,直到我遇到将编码图像作为可下载响应,在表单提交时包含将格式化为特定格式的图像文件,例如 webp、jpg、png 将是作为可下载文件发回给用户,下面是我的尝试。

public function image_format(Request $request){
    $this->validate($request, [
        'image' => 'required|file',
    ]);

    $raw_img = $request->file('image');

    $q = (int)$request->input('quality',100);
    $f = $request->input('format','jpg');

    $img = Image::make($raw_img->getRealPath())->encode('webp',$q);

    header('Content-Type: image/webp');

    echo $img;
}

但不幸的是,这不是我预期的输出,它只是显示了图像。

从这篇文章中,我使用代码并尝试实现我的目标

public function image_format(Request $request){
        $this->validate($request, [
            'image' => 'required|file',
        ]);

        $raw_img = $request->file('image');

        $q = (int)$request->input('quality',100);
        $f = $request->input('format','jpg');

        $img = Image::make($raw_img->getRealPath())->encode('webp',$q);
        $headers = [
            'Content-Type' => 'image/webp',
            'Content-Disposition' => 'attachment; filename='. $raw_img->getClientOriginalName().'.webp',
        ];

        $response = new BinaryFileResponse($img, 200 , $headers);
        return $response;
    }

但它不起作用,而是向我显示了这个错误

在此处输入图像描述

任何帮助,请想法?

标签: phplaravellumenintervention

解决方案


在 Laravel 中,您可以使用response()->stream(),但是,如评论中所述,Lumen 在响应中没有流方法。话虽这么说,该stream()方法几乎只是返回一个新实例的包装器StreamedResponse(它应该已经包含在您的依赖项中)。

因此,以下内容应该适合您:

$raw_img = $request->file('image');

$q = (int)$request->input('quality', 100);
$f = $request->input('format', 'jpg');

$img = Image::make($raw_img->getRealPath())->encode($f, $q);

return new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($img) {
    echo $img;
}, 200, [
    'Content-Type'        => 'image/jpeg',
    'Content-Disposition' => 'attachment; filename=' . 'image.' . $f,
]);

推荐阅读