简体   繁体   English

将现有的img转换为base64

[英]Convert an existing img to base64

I'm looking for an elegant way to convert an existing <img> on the document to base64 loaded <img> . 我正在寻找一种优雅的方法来将文档上的现有<img>转换为base64加载的<img> So simply the src url will be converted to base64 data. 因此,只需将src url转换为base64数据即可。

What's the best way to obtain this? 最好的方法是什么?

I've managed to make this work! 我设法做到了! (I got the same issue.) In the code below, img is the image DOM element: (我遇到了同样的问题。)在下面的代码中, img是图像DOM元素:

var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
img.crossOrigin = "anonymous";
canvas.getContext('2d').drawImage(img, 0, 0);
var dataUrl = canvas.toDataURL('image/png');

The line img.crossOrigin = "anonymous"; 这行img.crossOrigin = "anonymous"; helps to bypass CORS somehow, although I'm not sure if that's a "hack" and may be "fixed" at some point as I don't fully understand the issue with CORS here. 尽管我不确定这是否是“ hack”并且可能会在某些时候“修复”,但由于我不完全了解此处的CORS问题,因此它有助于以某种方式绕过CORS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM