ts 图片类型转换base64,url,file
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ts 图片类型转换base64,url,file相关的知识,希望对你有一定的参考价值。
参考技术A 1.url 转base64const Img = new Image();
let dataURL = '';
const base: number = Math.random();
Img.src = $imageUrl?v=$base ; //imageUrl图片url地址 ``模板字符串
Img.setAttribute('crossOrigin', 'Anonymous');
Img.onload = async function ()
const canvas = document.createElement('canvas');
const width = Img;
const height = Img;
canvas.width = width;
canvas.height = height;
canvas.getContext('2d')!.drawImage(Img, 0, 0, width, height);
dataURL = canvas.toDataURL('image/jpeg'); //dataURL 图片base64 类型
2.base64转file
const imgFile: any = base64ToBlob(img); //img 图片base64类型
function base64ToBlob(urlData: any)
const arr = urlData.split(',');
const mime = arr[0].match(/:(.*?);/)[1] || "image/png";
// 去掉url的头,并转化为byte
const bytes = window.atob(arr[1]);
// 处理异常,将ascii码小于0的转换为大于0
const ab = new ArrayBuffer(bytes.length);
// 生成视图(直接针对内存):8位无符号整数,长度1个字节
const ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++)
ia[i] = bytes.charCodeAt(i);
return new File([ab], "hhh.png",
type: mime
);
js,JQ 图片转换base64 base64转换为file对象
//将图片转换为Base64 function getImgToBase64(url,callback){ var canvas = document.createElement(‘canvas‘), ctx = canvas.getContext(‘2d‘), img = new Image; img.crossOrigin = ‘Anonymous‘; img.onload = function(){ canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img,0,0); var dataURL = canvas.toDataURL(‘image/png‘); callback(dataURL); canvas = null; }; img.src = url; } //将base64转换为文件 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}); } //将图片转换为base64 getImgToBase64(‘images/ruoshui.png‘,function(data){ var myFile = dataURLtoFile(data,‘testimgtestimgtestimg‘); console.log(myFile); });
以上是关于ts 图片类型转换base64,url,file的主要内容,如果未能解决你的问题,请参考以下文章
js,JQ 图片转换base64 base64转换为file对象