Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting raw image stream rather than jpeg, on-the-fly image resizing

Tags:

html

php

image

I have a PHP function that does on-the-fly image resizing for thumbnail creation.

I am having trouble as it's just displaying raw image stream instead of the actual image.

My code is using a function called thumbnail:

$thumbnail = thumbnail($item['filename'], 209, 137);
imagejpeg($thumbnail);

I've tried putting in:

header("Content-type: image/jpeg");

However, this just expects the full page to be an image. I have absolutely no idea where to go from here, been working at it for a while. I'd rather not save the image to disk although it's looking like this might be necessary.

like image 458
Craig Traynor Avatar asked May 22 '12 20:05

Craig Traynor


2 Answers

You either

Do it the normal way

This mean you point at one url, and serve the contents of one image:

<img src="myimage.php">

and myimage.php is a script that looks like:

header('Content-type: image/jpeg');
imagejpeg($thumbnail);
die;

This technique has the advantage of being.. the normal way of doing things.

OR

Output the image inline

Using data uris outputting the contents as a base64 encoded string

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

This technique is most appropriate with small images.

It has the advantage of meaning all the images are in the main http request - at the (possibly sizable) disadvantage of making the page harder to edit/build and possibly negating the benefits of browser caching (unless the html page is itself cached).

Being normal is easier

Regarding this statement in the question:

However, this just expects the full page to be an image

That's right - if you do it the normal way you want to point at your php script with the src attribute of an image tag, and server only an image - i.e. the exact same response as if you were pointing at an image file with a browser.

Unless you have a good reason to do things a different way - the "normal" way is a good place to start.

like image 148
AD7six Avatar answered Sep 28 '22 03:09

AD7six


You can point an html img tag to an php file.

<img src='thumbnail.php?file=<?php echo $item['filename']; ?>' />

Then on your php file you display the image and change the headers since all it is doing is displaying an image.

$thumbnail = thumbnail($_GET['filename'], 209, 137);
imagejpeg($thumbnail);

header("Content-type: image/jpeg");
like image 33
Pitchinnate Avatar answered Sep 28 '22 02:09

Pitchinnate