【问题标题】:force download image as response lumen + intervention image强制下载图像作为响应流明 + 干预图像
【发布时间】:2018-12-26 08:32:17
【问题描述】:

我在我的 Lumen 项目中使用intervention image 并且一切正常,直到我遇到将编码图像作为可下载响应,该响应在表单提交时包含将被格式化为特定格式的图像文件,例如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;
}

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

从此post,我使用代码并尝试实现我的目标

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;
    }

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

有什么建议吗?

【问题讨论】:

标签: php laravel lumen intervention


【解决方案1】:

在 Laravel 中,您可以使用 response()->stream(),但是,正如 cmets 中所提到的,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,
]);

【讨论】:

  • 我要导入什么类才能使 Image 类工作。流明
  • @richard4s 您是否想知道Image 类的完全限定命名空间?
  • @richard4s 应该和Intervention Image Docs一样:Intervention\Image\Facades\Image
猜你喜欢
  • 2019-07-04
  • 1970-01-01
  • 2021-06-19
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
相关资源
最近更新 更多