Display PNG image as response to jQuery AJAX request

前端 未结 3 1746
有刺的猬
有刺的猬 2020-11-29 00:41

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

相关标签:
3条回答
  • 2020-11-29 00:51

    This allows you to just get the image data and set to the img src, which is cool.

    var oReq = new XMLHttpRequest();
    oReq.open("post", '/somelocation/getmypic', true );        
    oReq.responseType = "blob";
    oReq.onload = function ( oEvent )
    {
        var blob = oReq.response;
        var imgSrc = URL.createObjectURL( blob );                        
        var $img = $( '<img/>', {                
            "alt": "test image",
            "src": imgSrc
        } ).appendTo( $( '#bb_theImageContainer' ) );
        window.URL.revokeObjectURL( imgSrc );
    };
    oReq.send( null );
    

    The basic idea is that the data is returned untampered with, it is placed in a blob and then a url is created to that object in memory. See here and here. Note supported browsers.

    0 讨论(0)
  • 2020-11-29 01:03

    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 + '" />');
    
    0 讨论(0)
  • 2020-11-29 01:11

    Method 1

    You should not make an ajax call, just put the src of the img element as the url of the image.

    This would be useful if you use GET instead of POST

    <script type="text/javascript" > 
    
      $(document).ready( function() { 
          $('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
      } );
    
    </script>
    

    Method 2

    If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme

    You'll need to encode the data to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data> into the img src

    as example:

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />
    

    To encode to base64:

    • in plain javascript, see How can you encode a string to Base64 in JavaScript?
    • in perl http://perldoc.perl.org/MIME/Base64.html
    • in php http://php.net/manual/en/function.base64-encode.php
    0 讨论(0)
提交回复
热议问题