Display PNG image as response to jQuery AJAX request

ZheFrench picture ZheFrench · May 29, 2012 · Viewed 126.1k times · Source

Is it possible to display an image returned by jQuery AJAX call, in the main stream of your HTML?

I have a script that draws an image with a header (image/PNG). When I simply call it in the browser, the image is displayed.

But when I make an AJAX call with jQuery on this script, I can't display a clean image, I have something with a lot of strange symbols. This is my script that makes the image with a header (image/PNG).

#!/usr/bin/perl 

use strict;
use CGI;
use Template;
use CGI::Carp qw(fatalsToBrowser);
use lib qw(lib);
use GD;

my $cgi    = new CGI;

my $id_projet            =  $cgi   -> param('id_projet') ;      # 

# Create a new image
my $image = new GD::Image(985,60) || die;
my $red =  $image->colorAllocate(255, 0, 0);
my $black =  $image->colorAllocate(0, 0, 0);

$image->rectangle(0,0,984,59,$black);
$image->string(gdSmallFont,2,10,"Hello $id_projet ",$black);
# Output the image to the browser

print $cgi -> header({-type => 'image/png',-expires => '1d'});

#binmode STDOUT;

print $image->png;

Then I have my main script with an AJAX call inside:

  <script type="text/javascript" > 

  $(document).ready( function() { 

  $.ajax({
  type: "POST",
  url:'get_image_probes_via_ajax.pl',
  contentType: "image/png",
  data: "id_projet=[% visual.projet.id %]",
  success: function(data){
  $('.div_imagetranscrits').html('<img src="' + data + '" />'); },
 } );

 </script>  

In my HTML file I have one div with class="div_imagetranscrits" to be filled with my image.

I don't see what I'm doing wrong. The other solution is to make my script write the image on disk and just get the path to include in the src to display it. But I was thinking it was possible to get the image with an image/PNG header directly from an AJAX request.

Answer

Timm picture Timm · May 29, 2012

You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php

Then in your ajax call change the success function to this:

$('.div_imagetranscrits').html('<img src="data:image/png;base64,' + data + '" />');