How to get image content (not URL) from an IMG element?

We use the Eclipse SWT WebBrowser control to render HTML pages for our Java application. If the page contains an image, we want to get an image. We can access the DOM to get the IMG element, but there seems to be no way to get the actual content (like image bytes) other than re-fetching the image using the image URL. (We can get the image URL through the 'src' attribute.) Is there a way to get the actual image bytes from the DOM?

+6
source share
2 answers

I'm not sure if this is what you are looking for, but basically you can just do a typed XHR (such as an ArrayBuffer) for the image source (it needs to be cached, so it doesn't need to be done). I assume that you are using an HTML5 compatible browser (either one that supports ArrayBuffer or the type you need). I assume that the document has at least one image with the correct source, see Fiddle for a working demo.

var img = document.querySelector('img'), xhr = new XMLHttpRequest(); xhr.open('GET', img.src, true); xhr.responseType = 'arraybuffer'; xhr.addEventListener('load', handleBuffer, false); xhr.send(); // Your image data ArrayBuffer, feel free to change the type. function handleBuffer (data) { var arryBuffer = data.target.response; } 

Script example

0
source

Check out https://developer.mozilla.org/en-US/docs/Web/API/FileReader , this will allow you to create base64 data URLs, it may not work depending on your browser versions.

-1
source

Source: https://habr.com/ru/post/894771/


All Articles