工作中常用到接口生成图片,返回的数据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