Ajax and returning image created by PHP GD

前端 未结 3 1821
囚心锁ツ
囚心锁ツ 2021-01-21 15:54

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         


        
相关标签:
3条回答
  • 2021-01-21 15:58

    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);
        })....
    
    0 讨论(0)
  • 2021-01-21 16:04

    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);
    }
    
    0 讨论(0)
  • 2021-01-21 16:14

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

    header("Content-Type: image/jpeg");
    header("Content-Length: " .sizeof($img_data));
    
    0 讨论(0)
提交回复
热议问题