views:

37

answers:

4

Despite setting directory permissions to 777, I still can't get a PHP script to write an image file that it generated to a directory on the server. So, rather than wrestling with that problem I thought, why not create a new one. Actually, I thought there might be an easier solution. Is it possible to take an image file (stream) that is generated on the server and "trick" the client so that the file doesn't have to exist in a directory on the server, so that the results can just be handed directly to the browser?

+1  A: 

Sure. Let's say you have the binary data in variable $im. Just do:

header("Content-type: image/png"); //change to suit your needs
echo $im;

PHP is perfectly capable of outputting non-HTML data.

Artefacto
@Michael Prescott - Using Artefacto's method above is perfectly compliant code and there will be no 'tricking' the browser into anything. The binary data is rad in as an object with mime type image/png, so provided it is png data, then this will work. For jpeg it will simply be header("Content-type: image/jpeg"); and for gif it will be header("Content-type: image/gif");
webfac
A: 

If using as a image URI

Convert your data to base64 (base64_encode) and use this as the URI:

data:MIMETYPE;base64,STUFF

e.g.

data:image/png;base64,iVBORAAAA...

If displaying image only

Just set the content type to the correct MIME and echo the contents.

Delan Azabani
Support for Data URI is buggy in the IE family though
Gordon
+1  A: 

Yes it is possible. Set the content type header to "image/png", then output the image data stream.

header("Content-type: image/png");
Travis Beale
A: 

You don't need to write the file if you are just making images on the fly. Just at the top of the php file set the file type to 'image/png' (or whatever) and write graphics instead of text.

<?php
$width = 300;
$height = 200;
$im     = imagecreate($width,$height);
$gray   = imagecolorallocate ($im,0xcc,0xcc,0xcc);
imagefilledrectangle($im,0,0,100,100,$grey);
header ("Content-type: image/png");
imagepng($im);
?> 
Woody