1

It is straightforward to download <img>s by downloading to their URLs. When the URLs became unaccessible, the images can still be seen on the monitor and right-click copy to clipboard, though can't do right-click save-as.

At this moment, is it possible to save the images to disk with JavaScript? (without using the mouse, certainly)

There are these kind of <img>s for testing on https://www.sunday-webry.com/viewer.php?chapter_id=3101, in which all blob:... images became immediately unaccessible, and even the speediest developers are not able to catch them.

The code is only expected to be run under the newest version of the state-of-the-art browsers.

user26742873
  • 919
  • 6
  • 21
  • Seems possible via canvas: https://stackoverflow.com/questions/934012/get-image-data-url-in-javascript testing ... – user26742873 Feb 24 '21 at 15:11
  • Success!! But be careful, the top answers using `width` and `height` instead of `naturalWidth` and `naturalHeight` may result in cropped images. Also I am wondering maybe there are methods without using canvas, since this extra process may make the image of less quality. – user26742873 Feb 24 '21 at 15:27
  • Maybe related: [getting ImageData without canvas](https://stackoverflow.com/questions/10754661/javascript-getting-imagedata-without-canvas) – user26742873 Feb 24 '21 at 15:32

1 Answers1

0

It is possible to via canvas (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);
    }}
);

Without modifing the property (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,/, "");
}

Notes that naturalWidth and naturalHeight are used instead of width and height, since the latter results into cropped images when the image is attributed or styled with fixed sizes.

However, by printing the picture to the canvas, the quality may decrease. I am wondering if there are methods that can get the images directly from the memory.

user26742873
  • 919
  • 6
  • 21