网站首页 > 基础教程 正文
主要识别图片类型,然后进行转换;
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});
}
猜你喜欢
- 2024-07-18 前端工程师进阶:Webpack的Bundle Split和Code Split区别和应用
- 2024-07-18 13条高效实用的JavaScript单行代码,关注收藏哦
- 2024-07-18 [总结]HTML+JS逆向混淆混合(js混淆反编译)
- 2024-07-18 网页版图像分割工具BodyPix:细分人体24个部位,iPhone流畅运行
- 2024-07-18 敲黑板!不容忽视的 JavaScript 性能优化技巧
- 2024-07-18 半身短裙服装打板纸样图纸之我见(半身裙打版数据)
- 2024-07-18 JavaScript中字符串的常用方法(js 字符串的方法)
- 2024-07-18 Webpack 中的代码分割(webpack 代码分割优点)
- 2024-07-18 一行JS代码,实现字符串内容翻转(js对字符串进行转码)
- 2024-07-18 Axure高级教程:如何从外部获取Axure中继器里的数据