Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to get image as bytes from a page (without redownloading)

Given an existing browser page with images is there a way to get the bytes from an <img> element using Javascript?

I am not seeing any methods in HTMLImageElement which would allow getting a byte array from the image element.

I have tried the following approach but this returns an empty byte array.

var img = document.querySelector('.my_image');
var body = document.querySelector('body');
var canvas = document.createElement('canvas');
canvas.height = img.height;
canvas.width = img.width;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
body.appendChild(canvas);
var imageBytes = context.getImageData(img.width, img.height, 1, 1).data;
console.log(imageBytes);
like image 236
ccpizza Avatar asked Mar 02 '23 08:03

ccpizza


1 Answers

The following js code will fetch an image from an existing <img..> element as base64 without re-downloading the image (assuming there is an image with the given selector on the page and that there is no canvas cors violation, which will be the case when you click the Run button below):

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var img = document.querySelector('img');
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
context.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
var base64String = canvas.toDataURL();
console.log(base64String);
<img src="http://placekitten.com/40/40">

NOTE: Running this code directly from the snippet will fail with an error message indicating a cross-domain violation. If you copy it to your own server then you'll get the base64-encoded content (❗️must not be a file:/// URL). If you can't avoid the cross-domain issue then then you'll need to use @DPardal's solution. It also works on a third-party domain if, for example, you inject the script with something like selenium.

like image 157
ccpizza Avatar answered Mar 05 '23 17:03

ccpizza