base64字符串 to File
const matchreg = srcBase64.match(/^data:image\/(\w+);base64,(.*)/);
if (!matchreg || matchreg.length !== 3) return null;
const [, mime, base64] = matchreg;
const bstr = atob(base64);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
const rs = new File([u8arr], `clipboard.${mime}`, { type: `image/${mime}` });
base64字符串 to Blob
上述代码最后一行改为
const rs = new Blob([u8arr], { type: `image/${mime}` });
base64字符串 to "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"
上述代码最后一行改为
const base64 = insert.image.replace(/^data:image\/\w+;base64,/, '');
const buf = new Buffer(base64, 'base64');
return buf.toString('binary')
base64字符串 保存为文件
const matchreg = srcBase64.match(/^data:image\/(\w+);base64,(.*)/);
if (!matchreg || matchreg.length !== 3) return null;
const [, mime, base64] = matchreg;
const buffer = Buffer.from(base64Data, 'base64');
fs.writeFileSync(`/usr/ttt.${mime}`, buffer)
图片url转base64字符串
const img = new Image();
img.src = url;
img.onload = () => {
const c = document.createElement('canvas') as HTMLCanvasElement;
c.width = width || img.naturalWidth;
c.width = c.width > 500 ? 500 : c.width;
c.height = (img.naturalHeight * c.width) / img.naturalWidth;
const cxt = c.getContext('2d') as CanvasRenderingContext2D;
cxt.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, c.width, c.height);
resolve(c.toDataURL('image/jpg'));
};
跨域图片url转base64字符串
function img2base64(url: string): Promise<string> {
return new Promise((resolve) => {
if (url.includes('data:image/')) {
resolve(url);
return;
}
const request = url.startsWith('https') ? httpsGet : httpGet;
request(url, (res) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const chunks: any = [];
let size = 0;
res.on('data', (chunk) => {
chunks.push(chunk);
size += chunk.length;
});
res.on('end', () => {
const data = Buffer.concat(chunks, size);
const base64 = data.toString('base64');
const ext = url.lastIndexOf('.') ? url.substr(url.lastIndexOf('.')) : 'jpg';
resolve(`data:image/${ext};base64,${base64}`);
});
});
});
}