最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Is there a way to load an Image in Javascript with data retrieved via an HTTP POST? - Stack Overflow

programmeradmin7浏览0评论

Is there any means to use AJAX to request an image file via an HTTP POST and then create a new Image with that data in HTML? Since you can't do this with the IMG tag, is it possible to do it with an Image javascript object?

Is there any means to use AJAX to request an image file via an HTTP POST and then create a new Image with that data in HTML? Since you can't do this with the IMG tag, is it possible to do it with an Image javascript object?

Share Improve this question asked Jun 21, 2011 at 19:58 ricosrealmricosrealm 1,6361 gold badge16 silver badges27 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

Yes that is possible.

When your serverscript opens the image files and encodes them as a base64 string, almost all browsers (except IE7 and below) can handle that. For instance:

jQuery('<img>', {
    src: 'data:image/jpeg;base64,' + someBase64EncodedString
}).appendTo(document.body);

A real-world example of this, can be found here: https://github./jAndreas/Supply

You might want to check out how to embed base64 encoded data as an image.

Here's an article that walks you through it.

http://danielmclaren./node/90

Try looking here: http://emilsblog.lerch/2009/07/javascript-hacks-using-xhr-to-load.html

If it returns the base64 encoded image data you could probably do it using data URIs and possibly Canvas.

Some "pseudo" code (using PHP and JS+jQuery) to demonstrate what you could do.

Server:

$image = new Imagick($imagePath);
echo 'data:image/png;base64,' . base64_encode($image);

Client:

$.ajax({
   method: "post",
   url: "/foo/bar.php",
   success: function (data) {
      $("<img />").attr("src", data).appendTo("#myContainer");
   }
});
发布评论

评论列表(0)

  1. 暂无评论