ajax接口返回图片类型数据,转为base64赋值给img
Posted 筑梦编程
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax接口返回图片类型数据,转为base64赋值给img相关的知识,希望对你有一定的参考价值。
工作中常用到接口生成图片,返回的数据JS怎么处理转成base64展示?
主要利用xhr2.0,responseType="blob"返回blob数据类型,代码如下:
第一种:
function fetchImageDataFromUrl(url, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.withCredentials = true;
xhr.onload = function() {
if (xhr.status < 400)
cb(this.response, null);
else
cb(null, "HTTP Status " + xhr.status + " for url " + url);
}
xhr.onerror = function(e) {
cb(null, e);
}
xhr.send();
}
fetchImageDataFromUrl(url, function () {
var reader = new FileReader();
reader.onload = function (event) {
var txt = event.target.result;
console.log(txt)
$('#sharePicPop img').attr('src', txt);
$('#sharePicPop').removeClass('dn');
};
reader.readAsDataURL(arrayBuffer);
})
第二种主要是利用arraybuffer
function fetchImageDataFromUrl(url, cb) {
// Fetch image data via xhr. Note that this will not work
// without cross-domain allow-origin headers because of CORS restrictions
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "arraybuffer";
xhr.withCredentials = true;
xhr.onload = function() {
if (xhr.status < 400)
cb(this.response, null);
else
cb(null, "HTTP Status " + xhr.status + " for url " + url);
}
xhr.onerror = function(e) {
cb(null, e);
}
xhr.send();
}
fetchImageDataFromUrl(url, function(arrayBuffer) {
var buffer = new Buffer(arrayBuffer.byteLength);
var view = new Uint8Array(arrayBuffer);
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
var type = 'image/jpeg';
var e = "data:" + type + ";base64," + buffer.toString("base64");
$('#sharePicPop img').attr('src', e);
$('#sharePicPop').removeClass('dn');
})
第三种利用canvas转换base64数据
var imgUrl = '' // 带有参数的的ajax接口url
var img = new Image();
img.crossOrigin = location.host;
img.src = imgUrl;
img.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height);
$('#sharePicPop img')[0].src = canvas.toDataURL('image/jpeg');
$('#sharePicPop').removeClass('dn');
common.stopScroll();
};
img.onerror = function(e,s) {
console.log(e);
console.log(s);
}
参考文章:http://javascript.ruanyifeng.com/stdlib/arraybuffer.html
*声明:本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜。
以上是关于ajax接口返回图片类型数据,转为base64赋值给img的主要内容,如果未能解决你的问题,请参考以下文章
eggjs 怎么实现返回 base64 图片的接口给前端回显头像?