php - 强制下载图像作为响应流明 + 干预图像
问题描述
我在我的 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;
}
但它不起作用,而是向我显示了这个错误
任何帮助,请想法?
解决方案
在 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,
]);
推荐阅读
- php - 使用 !empty() 函数检查是否足以防止 PHP 7+ 中的通知和警告消息?
- python - TensorFlow/keras ,训练期间未使用 GPU
- python - PyPy:无法使用 pip 安装 sasl 包
- javascript - 在 JAVASCRIPT 中打印文本文件
- drools - 我们有什么方法可以在 Drools 规则引擎中执行 drl 文件的测试覆盖吗?
- spring-boot - Spring Boot 测试不在 gradle 中运行
- sql - 连接多个查询的输出
- java - 如何在回调类中传递不同的泛型?
- webpack - 有没有办法在 webpack 上运行 watch 并按顺序运行 grunt
- scala - 如何知道a是否是Zeppelin上的scala中定义的变量