JavaScript图片转base64
时间: 2023-05-10 17:55:59 浏览: 128
可以使用canvas将图片转换为base64编码,以下是示例代码:
```javascript
function convertImageToBase64(imageUrl) {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL('image/png');
resolve(dataURL);
};
img.onerror = function() {
reject(new Error('Failed to load image'));
};
img.src = imageUrl;
});
}
// 使用示例
convertImageToBase64('https://example.com/image.png')
.then(base64 => console.log(base64))
.catch(error => console.error(error));
```
这段代码可以将指定URL的图片转换为base64编码,并返回一个Promise对象。如果图片加载失败,则会reject一个Error对象。
阅读全文