简体   繁体   中英

Displaying jpeg using imagejpeg

I am trying to understand methods of displaying an image in a browser. This works:

echo '<img src="data:image/jpeg;base64,'. base64_encode($photoData) .'" />';                                        

But this does not:

$image = imagecreatefromstring($photoData);       
header('Content-Type: image/jpeg');
imagejpeg($image);

It displays the data rather than the image. Can anyone explain what I am missing?

Try below code:

<?php 

header('Content-Type: image/jpeg');

$exploded = explode(',', $photoData, 2); // limit to 2 parts, i.e: find the first comma
$encoded = $exploded[1]; // pick up the 2nd part
$decoded = base64_decode($encoded);

$im = imagecreatefromstring($decoded);       

$width = "500px";
$height = "400px";
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $width, 'height' => $height]);

imagejpeg($im2);
// Free up memory
imagedestroy($im2);

?>

Image crop example PHPImagecrop

Make sure:

That your page only prints the image because if it's contain any string or other errors it won't show the image.

I used this reference to solve your issue, imagecreatefromstring using image with data:image/png;base64,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM