专业编程基础技术教程

网站首页 > 基础教程 正文

js图片数据转换操作(图片转js代码)

ccvgpt 2024-07-18 12:49:04 基础教程 2 ℃

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

function btoimg(buffer) {

js图片数据转换操作(图片转js代码)

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});

}

Tags:

猜你喜欢

最近发表
标签列表