首页 > 解决方案 > 不使用 URL下载

问题描述

<img>通过下载到它们的 URL来下载 s 很简单。当 URL 无法访问时,仍然可以在监视器上看到图像并右键单击复制到剪贴板,但不能右键单击另存为。

此时,是否可以使用 JavaScript 将图像保存到磁盘?(当然不用鼠标)

在https://www.sunday-webry.com/viewer.php?chapter_id=3101上有这类<img>用于测试的 s ,其中所有图像都立即无法访问,即使是最快的开发人员也无法捕捉到它们。blob:...

该代码预计只能在最先进的浏览器的最新版本下运行。

标签: javascriptblob

解决方案


可以通过画布(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,/, "");
}

注意naturalWidthnaturalHeight用于代替widthand height,因为当图像被赋予属性或以固定尺寸设置样式时,后者会导致裁剪图像。

但是,通过将图片打印到画布上,质量可能会降低。我想知道是否有可以直接从内存中获取图像的方法。


推荐阅读