【问题标题】:Download <img>s without using their URL在不使用 URL 的情况下下载 <img>
【发布时间】:2021-05-26 22:13:42
【问题描述】:

通过下载到他们的 URL 来下载&lt;img&gt;s 很简单。当 URL 无法访问时,仍然可以在显示器上看到图像并右键单击复制到剪贴板,但不能右键单击另存为。

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

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

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

【问题讨论】:

  • 似乎可以通过画布:stackoverflow.com/questions/934012/… testing ...
  • 成功!!但请注意,使用widthheight 而不是naturalWidthnaturalHeight 的最佳答案可能会导致图像被裁剪。另外我想知道是否有不使用画布的方法,因为这个额外的过程可能会使图像质量降低。

标签: javascript blob


【解决方案1】:

可以通过画布(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 用于代替 widthheight,因为当图像属性或样式固定为固定尺寸时,后者会导致图像被裁剪。

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

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 2019-03-24
    • 2013-10-28
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2013-01-11
    • 2019-03-25
    • 1970-01-01
    相关资源
    最近更新 更多