I'm trying to display a png image in PHP (Laravel)
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?
Try it! Keep it simple :)
$img = file_get_contents(public_path('yourimage.jpg'));
return response($img)->header('Content-type','image/png');
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 :
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]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With