Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display image in PHP (Laravel)

Tags:

php

laravel

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?

like image 716
Alex Avatar asked Nov 20 '16 21:11

Alex


2 Answers

Try it! Keep it simple :)

$img = file_get_contents(public_path('yourimage.jpg'));
return response($img)->header('Content-type','image/png');
like image 142
KmasterYC Avatar answered Oct 14 '22 01:10

KmasterYC


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 :

Method 1 use 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:

$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.

like image 37
Sanchit Gupta Avatar answered Oct 13 '22 23:10

Sanchit Gupta