龙空技术网

js图片数据转换操作

九重天劫 105

前言:

眼前看官们对“js的图片切换”大致比较关心,小伙伴们都需要知道一些“js的图片切换”的相关文章。那么小编在网摘上搜集了一些有关“js的图片切换””的相关文章,希望小伙伴们能喜欢,姐妹们一起来学习一下吧!

主要识别图片类型,然后进行转换;

function btoimg(buffer) {

var mime;

var a = new Uint8Array(buffer);

var nb = a.length;

if (nb < 4)

return null;

var b0 = a[0];

var b1 = a[1];

var b2 = a[2];

var b3 = a[3];

if (b0 == 0x89 && b1 == 0x50 && b2 == 0x4E && b3 == 0x47)

mime = 'image/png';

else if (b0 == 0xff && b1 == 0xd8)

mime = 'image/jpeg';

else if (b0 == 0x47 && b1 == 0x49 && b2 == 0x46)

mime = 'image/gif';

else

return null;

var binary = "";

for (var i = 0; i < nb; i++)

binary += String.fromCharCode(a[i]);

var base64 = window.btoa(binary);

var image = new Image();

//image.onload = onLoad;

image.id = "upload";

image.src = 'data:' + mime + ';base64,' + base64;

return image;

}

/*

var val = [...];

var img = btoimg(val);

document.getElementById("result").append(img);

*/

将image base64转换成File对象

function dataURLtoFile(dataurl, filename) {

var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],

bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);

while(n--){

u8arr[n] = bstr.charCodeAt(n);

}

return new File([u8arr], filename, {type:mime});

}

/*

var f = dataURLtoFile('data:image/png;base64,......','test.png');

console.log(f);

*/

将byte[]转换成File对象

根据上面的思路直接对字节数组进行转换成FILE对象;

function btof(buffer, filename) {

var mime;

var a = new Uint8Array(buffer);

var nb = a.length;

if (nb < 4)

return null;

var b0 = a[0];

var b1 = a[1];

var b2 = a[2];

var b3 = a[3];

if (b0 == 0x89 && b1 == 0x50 && b2 == 0x4E && b3 == 0x47){

mime = 'image/png';

suffix = 'png';

}else if (b0 == 0xff && b1 == 0xd8){

mime = 'image/jpeg';

suffix = 'jpg';

}else if (b0 == 0x47 && b1 == 0x49 && b2 == 0x46){

mime = 'image/gif';

suffix = 'gif';

}else{

return null;

suffix = '';

}

return new File([a], filename+'.'+suffix, {type:mime});

}

标签: #js的图片切换 #js把图片转换成base64 #js背景图片切换 #js实现图片切换