可以通过画布(https://stackoverflow.com/a/58653042/8535456):
Object.defineProperty
(
HTMLImageElement.prototype,'toDataURL',
{enumerable:false,configurable:false,writable:false,value:function(m,q)
{
let c=document.createElement('canvas');
c.width=this.naturalWidth; c.height=this.naturalHeight;
c.getContext('2d').drawImage(this,0,0); return c.toDataURL(m,q);
}}
);
不修改属性(https://stackoverflow.com/a/934925/8535456):
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.naturalWidth
canvas.height = img.aturalHeight
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
请注意,naturalWidth 和 naturalHeight 用于代替 width 和 height,因为当图像属性或样式固定为固定尺寸时,后者会导致图像被裁剪。
但是,通过将图片打印到画布上,质量可能会降低。我想知道是否有可以直接从内存中获取图像的方法。