显示 PNG 图像作为对 jQuery AJAX 请求的响应 [英] Display PNG image as response to jQuery AJAX request

查看:46
本文介绍了显示 PNG 图像作为对 jQuery AJAX 请求的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 HTML 的主流中显示由 jQuery AJAX 调用返回的图像?

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

我有一个脚本可以绘制带有标题的图像(图像/PNG).当我在浏览器中简单地调用它时,就会显示图像.

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.

但是当我在这个脚本上使用 jQuery 进行 AJAX 调用时,我无法显示干净的图像,我有很多奇怪的符号.这是我的脚本,它使图像带有标题(图像/PNG).

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;

然后我的主脚本里面有一个 AJAX 调用:

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>  

在我的 HTML 文件中,我有一个带有 class="div_imagetranscrits" 的 div 用于填充我的图像.

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

我不明白我做错了什么.另一种解决方案是让我的脚本将图像写入磁盘,然后获取包含在 src 中的路径以显示它.但我认为可以直接从 AJAX 请求中获取带有图像/PNG 标头的图像.

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.

推荐答案

你需要将图片发送回 base64 编码,看这个:http://php.net/manual/en/function.base64-encode.php

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

然后在您的 ajax 调用中将成功函数更改为:

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

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

这篇关于显示 PNG 图像作为对 jQuery AJAX 请求的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆