output a base64_encoded image

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
ed209
Forum Contributor
Posts: 153
Joined: Thu May 12, 2005 5:06 am
Location: UK

output a base64_encoded image

Post by ed209 »

I am reading a mixture of plain text and images. There are various types of each i.e. gif, jpeg, png...

I would like to display them all on the same page but once you set a header, you can't then set another one for a different content type. Is there an easy way round this?

Code: Select all

loop going through different parts being read{

$type = "image/jpeg"; // or image/gif or image/png or text/plain
$file = "some ascii string";

header("Content-type: $type");
echo($file);

}
At the moment I am sending $type and $file as GET to another script, but I think they're too long and my images are corrupted. Alternatively, I could check for images and

Code: Select all

echo '<img src="see_the_file.php?type='.$type.'&file='.urlencode(base64_encode($file)).'" />
but I think I'll still have the same problem.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

images are sent in separate streams apart from the page code, so your second one is the only real way. If $file is a filename then yes, the images will be corrupt as echo will not load the file referenced readfile() is useful for this. If $file is the binary data, the resultant URL could indeed by quite long, long enough to get truncated by your browser or the server depending on various settings of course. In this case, I'd either write the data to an actual file or store it in a database to make referencing simple.
User avatar
ed209
Forum Contributor
Posts: 153
Joined: Thu May 12, 2005 5:06 am
Location: UK

Post by ed209 »

the files were only small, but even so they would not send as part of a URL. In the end I just saved the files to disc and viewed them manually. It was only for testing though.

Code: Select all

function create_image($type, $img_data){
	$myFile = microtime().".".$type;
	$fh = fopen($myFile, 'w');
	fwrite($fh, $img_data);
	fclose($fh);
	chmod($myFile, 0777);
}

create_image("jpg", "some ascii str");
Post Reply