Ajax and returning image created by PHP GD

左心房为你撑大大i 提交于 2019-12-20 03:15:04

问题


I have a PHP script that generates an image with PHP GD. After it generates the image, it saves it, and send this output when called by Ajax:

imagejpeg($img_data, 'filename.jpg');
echo '<img src="/filename.jpg.jpg">';

And after that, the image is shown on the page, and everything is fine. But, I don't want to create an image every time. Is there some way that I return by Ajax only $raw_data string and show the image? I tried like this:

echo $img_data;

But no luck, only thing that is returned is a few ?.

Here is my jQuery Ajax code:

$.ajax({
  type: 'POST',
  data: {
    action: 'update_image',
    //some instructions for creating the image
  },
  url: 'script.php',
  success: function(msg) {
    $('#somediv').append(msg);
  }
});

回答1:


base64 encode the image and return that, then you can do an <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA......." />

On the PHP side

$image = base64_encode($imageGDRender);
echo json_encode(array('image'=>$image));

That will return your json back to your jquery

then on the ajax side

$.ajax({
    ...
    success: function(data) {
        var base64Image = data.image;
        ...now put it in your image
        $('#image').attr('src','data:image...'+base64Image);
    })....



回答2:


Here is solution:

PHP code:

ob_start();
imagejpeg($im);
$outputBuffer = ob_get_clean();
$base64 = base64_encode($outputBuffer);
echo '<img src="data:image/jpeg;base64,'.$base64.'" />';

On user side (in JQuery):

success: function(data) {
        $('#somediv').append(data);
}



回答3:


You should modify the header before doing the echo $img_data;

header("Content-Type: image/jpeg");
header("Content-Length: " .sizeof($img_data));


来源:https://stackoverflow.com/questions/12144479/ajax-and-returning-image-created-by-php-gd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!