将图片url转为base64
时间: 2023-10-03 09:07:04 浏览: 97
好的,可以使用以下JavaScript代码将图片的URL转换为Base64编码:
```javascript
function convertImgToBase64(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
// 调用示例
convertImgToBase64('https://example.com/image.jpg', function(base64Img){
console.log('转换后的Base64编码为:', base64Img);
});
```
其中,`url`参数是原始图片的URL,`callback`参数是转换完成后的回调函数,`outputFormat`参数是输出的编码格式,默认为`image/png`。
阅读全文