图片转base64
2023-11-07 本文已影响0人
隔壁甜言
1、图片file对象转base64
//将图片文件对象转成base64值
//例如:使用上传图片antd-Upload组件时,就可能用到
import React, { useState } from 'react';
import { Upload, Button } from 'antd';
export default function Img() {
const [base64, setBase64] = useState('');
const imgFileToBase64 = (file: File) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
};
//上传图片,将上传到图片base64放到其他img中展示
return (
<div>
<Upload
name="file"
customRequest={async (info: any) => {
const base64ImgWhole: any = await imgFileToBase64(info.file);
//如果需要将图片base64给后台,则需要将data.*base64去掉
const base64Img = base64ImgWhole.replace(/^data.*base64,/, '');
setBase64(base64ImgWhole);
}}
showUploadList={false}
>
<Button>上传图片</Button>
</Upload>
{base64 && <img src={base64} />}
</div>
);
}
2、将图片的url转为base64
//通过canvas.toDataURL()将图片转成base64值
const getImgBase64 = (url: any, callback: any) => {
//创建image对象
let img = new Image();
img.src = url;
//setAttribute()设置元素属性
//设置图片允许跨域,否则canvas转base64时,toDataURL会报错
img.setAttribute('crossOrigin', 'anonymous');
img.onload = () => {
//创建canvas元素
const canvas = document.createElement('canvas');
//使用naturalWidth,naturalHeight使图片更准确
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext('2d');
ctx?.drawImage(img, 0, 0);
const base64 = canvas.toDataURL('image/png');
//回调函数 将data:image/png;base64,去掉后,可传给后台
callback(base64.replace("data:image/png;base64,", ""));
};
}