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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章