Sending and receiving imagepng output via json encode AJAX

LITguy picture LITguy · Jul 30, 2012 · Viewed 14.7k times · Source

I created a PNG image using PHP GD Library, added some text based on user input, and instead of saving it, I want to display it until user commits to changes.

They will add a few words, change a font, etc. so it needs to display their changes. The only way I got this to work is to save the image to the server, but it saves dozens of images for dozens of slight changes the user makes. I need to either overwrite the file, or do the below idea if it is proper. The idea would be to create a temp file to manipulate.

So, how do I send it to the "success callback" just like the other variables I processed? I read about how to use ob_get_contents() and I believe that is supposed to somehow store the image temporarily. Is this how it works?

How do I display the image on the form page (not the processing PHP page) and is this a good plan to prevent saving to the server until the user commits?

// more image manipulation code above

ob_start();
imagepng( $my_img );
$imageData = ob_get_contents();
ob_clean(); 

$results = array(
'price' => $_GET['priceX'],
'imageprocessed' => base64_encode($imageData) <<<  EDIT change based on answer.
);

$json = json_encode($results);
echo $json;
?>

EDIT: This is the javascript used in the success callback to receive the base64_encode.

<script type="text/javascript">
function doGen(){
var priceX = $('#couponprice').val();

$.get('processimage.php',
{priceX:priceX}, 
function(data) {
var imgFldr = '/images/';                   
data = $.parseJSON(data);
$('.price-placeholder').html(data.price);
var imageCallback = (data.couponnamecall);
$('#couponbuilt img').attr('src', 'data:image/jpeg;base64,' + imageCallback);
// ...
});
return false;
};
</script>   

Answer

MarcDefiant picture MarcDefiant · Jul 30, 2012

You could base64encode($imageData).

On the client side you simply create an data url out of the base64 encoded data and pass it into the src-attribute of an image tag.

I tested it out:

PHP code

ob_start();
imagepng($my_img);
$imageData = ob_get_contents();
ob_clean(); 

$results = array(
  'price' => $_GET['priceX'],
  'image' => base64_encode($imageData)
);

$json = json_encode($results);
echo $json;

Javascript code:

$.getJSON("/ajax-script.php", function(data) {
  $("#element").append($("<img />").attr('src', 'data:image/png;charset=utf8;base64,' + data.image));
});