JavaScript 将png转换为Base64格式字符串并返回
时间: 2023-05-11 12:01:58 浏览: 142
将图片toBase64字符串
5星 · 资源好评率100%
可以使用canvas来实现将png转换为Base64格式字符串的功能,代码如下:
```javascript
function pngToBase64(pngUrl) {
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 = pngUrl;
});
}
```
调用方式如下:
```javascript
pngToBase64('https://example.com/image.png')
.then(base64 => console.log(base64))
.catch(error => console.error(error));
```
其中,`pngUrl`为png图片的URL地址,`base64`为转换后的Base64格式字符串。
阅读全文