Ajax和PHP支持GD创建返回形象 [英] Ajax and returning image created by PHP GD

查看:105
本文介绍了Ajax和PHP支持GD创建返回形象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生成与PHP GD图像的PHP脚本。之后它生成的图像,将其保存,并将其发送输出,当阿贾克斯被称为:

  imagejpeg($ img_data,'filename.jpg');
回声'< IMG SRC =/ filename.jpg.jpg>';
 

而在此之后,该图像显示在页面上,并且一切都很好。但是,我不希望每次都创建一个图像。有没有一些方法,我回到阿贾克斯仅 $ raw_data 字符串,并显示图像?我想是这样的:

 回声$ img_data;
 

但没有运气,只有返回的东西是几?

下面是我的jQuery的Ajax code:

  $。阿贾克斯({
  键入:POST,
  数据: {
    动作:update_image,
    //一些说明创建图像
  },
  网址:script.php的,
  成功:函数(MSG){
    $('#somediv)追加(MSG)。
  }
});
 

解决方案

的base64 EN $ C C图像$,并返回,那么你可以做一个< IMG SRC =数据:图像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAAADIA ....../>

在PHP端

  $形象= base64_en code($ imageGDRender);
回声json_en code(阵列('形象'=> $图片));
 

这将返回您JSON回你的jQuery

然后在AJAX方

  $。阿贾克斯({
    ...
    成功:功能(数据){
        VAR base64Image = data.image;
        ......现在把它放在你的形象
        $('#图像)ATTR(SRC,数据:图像...+ base64Image)。
    })....
 

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);
  }
});

解决方案

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);
    })....

这篇关于Ajax和PHP支持GD创建返回形象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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