在 PHP (Laravel) 中显示图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40709757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:46:59  来源:igfitidea点击:

Display image in PHP (Laravel)

phplaravel

提问by Alex

I'm trying to display a png image in PHP (Laravel)

我正在尝试在 PHP (Laravel) 中显示一个 png 图像

So far I've tried

到目前为止我已经尝试过

$response =  Response::make(readfile(public_path() . 
"/img/$image_name.png", 200))->header('Content-Type', 'image/png');
return $response;

and this

和这个

$file = public_path() . "/img/$image_name.png";
$im = imagecreatefrompng($file);
header('Content-Type: image/png');
imagePNG($im);
imagedestroy($im);

I always get something like this instead of an actual image

我总是得到这样的东西而不是实际图像

?PNG  IHDR:?c PLTE????>tRNS?* ?< pHYs???+uIDAT(?e?? AJs *?[P???@8???Y?:????s?A?"D?!B?"D?!B?"D?!C~????}??Q??N?+'??bP?.a&^O)%5Y\?L????.?9??IEND?B`?

When I use jpeg header and jpeg image it starts showing the actual image in browser, but for some reason it doesn't work for png images. Have anyone faced a similar problem?

当我使用 jpeg 标题和 jpeg 图像时,它开始在浏览器中显示实际图像,但由于某种原因它不适用于 png 图像。有没有人遇到过类似的问题?

回答by KmasterYC

Try it! Keep it simple :)

尝试一下!把事情简单化 :)

$img = file_get_contents(public_path('yourimage.jpg'));
return response($img)->header('Content-type','image/png');

回答by Sanchit Gupta

You should find the mime dynamicaly using laravel default file facade File::mimeType($path)because as you mentioned that it is working fine with another image type like jpeg. I think this may happen because sometime we change file extension for testing or may be file have some issue with its header etc. You can use the following code :

您应该使用 Laravel 默认文件外观动态地找到 mime,File::mimeType($path)因为正如您所提到的,它可以与 jpeg 等其他图像类型一起正常工作。我认为这可能是因为有时我们更改文件扩展名以进行测试,或者文件的标题等可能存在问题。您可以使用以下代码:

Method 1 use Response::stream:

方法一使用Response::stream

$path = public_path() . "/img/$image_name.png";
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::stream(function() use($file) {
  echo $file;
}, 200, ["Content-Type"=> $type]);

Method 2 use Response::make:

方法二使用Response::make

$path = public_path() . "/img/$image_name.png";
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;

Hope it will help.

希望它会有所帮助。

回答by user3482682

I suggest you use this plugin: http://image.intervention.io/

我建议你使用这个插件:http: //image.intervention.io/

回答by Xiaobing Mi

perhaps you forgot install php-gd extension on your server

也许你忘了在你的服务器上安装 php-gd 扩展

sudo apt-get install php-gd

or

或者

sudo yum install php-gd