简体   繁体   English

显示 PNG 图像作为对 jQuery AJAX 请求的响应

[英]Display PNG image as response to jQuery AJAX request

Is it possible to display an image returned by jQuery AJAX call, in the main stream of your HTML?是否可以在您的 HTML 的主 stream 中显示 jQuery AJAX 调用返回的图像?

I have a script that draws an image with a header (image/PNG).我有一个用 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.但是当我在这个脚本上用 jQuery 进行 AJAX 调用时,我无法显示干净的图像,我有很多奇怪的符号。 This is my script that makes the image with a header (image/PNG).这是我使用 header(图像/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:然后我的主脚本里面有一个 AJAX 调用:

  <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.在我的 HTML 文件中,我有一个带有class="div_imagetranscrits"的 div 来填充我的图像。

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.另一种解决方案是让我的脚本将图像写入磁盘并获取要包含在 src 中的路径以显示它。 But I was thinking it was possible to get the image with an image/PNG header directly from an AJAX request.但我认为可以直接从 AJAX 请求中获取带有 image/PNG header 的图像。

You'll need to send the image back base64 encoded, look at this: http://php.net/manual/en/function.base64-encode.php 您需要将图像发送回base64编码,请看: http//php.net/manual/en/function.base64-encode.php

Then in your ajax call change the success function to this: 然后在你的ajax调用中将success函数更改为:

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

Method 1 方法1

You should not make an ajax call, just put the src of the img element as the url of the image. 你不应该进行ajax调用,只需将img元素的src作为图像的url。

This would be useful if you use GET instead of POST 如果您使用GET而不是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 方法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 如果你想对那个图像进行POST并按照你的方式进行操作(尝试在客户端解析图像的内容,你可以尝试这样的事情: 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 您需要将data编码为base64,然后您可以将data:[<MIME-type>][;charset=<encoding>][;base64],<data>放入img src

as example: 例如:

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

To encode to base64: 要编码到base64:

This allows you to just get the image data and set to the img src, which is cool. 这允许您只获取图像数据并设置为img src,这很酷。

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. 基本思想是数据被返回到未被篡改,它被放置在blob中,然后在内存中为该对象创建一个url。 See here and here . 看到这里这里 Note supported browsers. 注意支持的浏览器

Thanks to above answers and after some more searching able to come up with below solution for Spring Boot application.多亏了上述答案,经过更多搜索后,我们才能为 Spring Boot 应用程序提出以下解决方案。

HTML HTML

<div class="row">
     <div class="col-11" id='img_div'>
     </div>
</div>

Javascript Javascript

function loadImage() {

        $.ajax({
            type: "GET",
            url: contextPath+"/loadImage",
            data: null,
            dataType: 'text',
            cache: false,
            timeout: 600000,
            success: function (data) {
                $('#img_div').html('<img id="img" src="data:image/png;base64,' + data + '" />');
                
            },
            error: function (e) {
                //handle error
            }
        });
    
    }

Controller Method Controller 方法

@GetMapping("/loadImage")
@ResponseBody
private String loadImagefromExternalFolder(HttpServletRequest request){     
    String encodedString = "";
    
    try {       
        RandomAccessFile f =  new RandomAccessFile("C:\\your_folder_path\\your_img.PNG", "r");
        byte[] b = new byte[(int)f.length()];
        f.readFully(b);
        
        encodedString = Base64.getEncoder().encodeToString(b);

    }catch (Exception e) {
        // handle error
    }


    return encodedString;
    
}

Update for 2022: Use blobs -- you no longer need to waste time and bandwidth converting to base64. 2022 年更新:使用 blob——您不再需要浪费时间和带宽转换为 base64。

Here is the example from https://developer.mozilla.org/en-US/docs/Web/API/Response#fetching_an_image这是来自https://developer.mozilla.org/en-US/docs/Web/API/Response#fetching_an_image的示例

const image = document.querySelector('.my-image');
fetch('flowers.jpg')
.then(response => response.blob())
.then(blob => {
  const objectURL = URL.createObjectURL(blob);
  image.src = objectURL;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM