Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: create image with ImagePng and convert with base64_encode in a single file?

Tags:

php

image

gd

I have created an image with ImagePng(). I dont want it to save the image to the file system but want to output it on the same page as base64 encode inline Image, like

print '<p><img src="data:image/png;base64,'.base64_encode(ImagePng($png)).'" alt="image 1" width="96" height="48"/></p>';

which does not work.

Is this possible in a single PHP file at all?

Thanks in advance!

like image 292
Romaeus Percival Avatar asked Feb 21 '12 01:02

Romaeus Percival


2 Answers

I had trouble using the ob_get_contents() when using PHP with AJAX, so I tried this:

$id = generateID(); //Whereas this generates a random ID number
$file="testimage".$id.".png";
imagepng($image, $file);
imagedestroy($image);
echo(base64_encode(file_get_contents($file)));
unlink($file);

This saves a temporary image file on the server and then it is removed after it is encoded and echoed out.

like image 38
SyntaxLAMP Avatar answered Sep 16 '22 15:09

SyntaxLAMP


The trick here will be to use output buffering to capture the output from imagepng(), which either sends output to the browser or a file. It doesn't return it to be stored in a variable (or base64 encoded):

// Enable output buffering
ob_start();
imagepng($png);
// Capture the output and clear the output buffer
$imagedata = ob_get_clean();

print '<p><img src="data:image/png;base64,'.base64_encode($imagedata).'" alt="image 1" width="96" height="48"/></p>';

This is adapted from a user example in the imagepng() docs.

like image 173
Michael Berkowski Avatar answered Sep 20 '22 15:09

Michael Berkowski