Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

We are using the Eclipse SWT WebBrowser control to render HTML pages for our Java application. If the page contains an image, we want to get the image content. We can access the DOM to get the IMG element, but there doesn't seem to be a way to get the actual content (i.e. the bytes of the image) other than re-fetching the image using the image URL. (We can get the image URL via the 'src' attribute.) Is there any way to get the actual bytes of the image from the DOM?

like image 511
ghirschhorn Avatar asked Aug 10 '11 22:08

ghirschhorn


1 Answers

I am not sure if this is what you are looking for, but basically you can just make a typed XHR (such as ArrayBuffer) to the image source (it should be cached, so no real hit by doing this). I am assume you are using an HTML5 compliant browser (or such that supports ArrayBuffer or the type you need). I am assuming the document has at least one image with a proper source, see Fiddle for 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;
}

Sample Fiddle

like image 164
joseeight Avatar answered Nov 12 '22 16:11

joseeight