前端png图片转base64
时间: 2023-11-15 21:57:00
浏览: 491
可以使用canvas将png图片转换为base64编码。具体步骤如下:
1. 创建一个Image对象,并将png图片的url赋值给它。
2. 等待Image对象加载完成,然后将它绘制到一个canvas上。
3. 使用canvas的toDataURL方法将canvas上的图像转换为base64编码。
以下是示例代码:
```javascript
function pngToBase64(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL('image/png');
resolve(dataURL);
img.onerror = reject;
img.src = url;
```
最低
0.47元/天
开通会员,查看完整答案

成为会员后, 你将解锁


相关推荐

















