注意能够解码和显示从服务器接收的分块图像 [英] Note able to decode and displaychunked image received from server

查看:111
本文介绍了注意能够解码和显示从服务器接收的分块图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从对服务器的ajax调用中接收分块编码的图像. 如何在客户端中显示该分块的图像? 我的代码如下:-

I am receiving an image in chunked encoding from a ajax call to server. how to display that chunked image in client? My code is below:-

$.ajax({ 
         url: service url, 
         type: 'POST', 
         headers: {
            "accept": "image/jpeg",
            "content-Type": "application/json",
                },
         success: function(data) { 
         console.log(data.responseText);
         $('#imageDiv').html('<img src="data:image/jpeg,base64'+data+'"  height="200px" width="500px" />');

          }
   });

但是给出这样的结果:

C C A

��C��C��A���

推荐答案

在实践中,我经常看到人们这样做:

In practice, I often see people do like this:

例如,服务器支持GET而不是POST图像,

Server support GET instead of POST for image for example, then:

$('#img').attr('src', '/images/pic1.jpg?width=200&height=200');

如果从服务器返回base64字符串:

if return base64 string from server:

$.ajax({ 
    url: service url, 
    type: 'GET',
    success: function(data) { 
         $('#yourDiv').html('<img src="data:image/jpeg,base64'+data+'"/>');
    }
});


如果您无法修改服务器代码,则可以在现代浏览器中从二进制文件转换base64:

// Code taken from MatthewCrumley (http://stackoverflow.com/a/934925/298479)
function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to guess the
    // original format, but be aware the using "image/jpg" will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

这篇关于注意能够解码和显示从服务器接收的分块图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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