sc45
sc45

Reputation: 1956

ImageData of an externally loaded Image?

I load an external image and draw it on the Canvas element like so:

var canvas = document.getElementById('canvas1');
var context = canvas.getContext('2d');
var image = new Image();
image.onload = function(evt) { context.drawImage(evt.target, 0, 0); }
image.src = "test.jpg";

But I want to get the ImageData. So after calling context.drawImage, I do this:

var imagedata = canvas.getImageData();
manipulate(imagedata); // modifies imagedata.data
context.putImageData(imagedata, 0, 0);

Is that the only way to get the imageData of an externally loaded image? Drawing the image on canvas & then getting the imagedata seems awfully slow. Am I missing something?

Thanks!

Upvotes: 3

Views: 2813

Answers (2)

olliej
olliej

Reputation: 36763

There is no direct way of getting the ImageData, it is inefficient but on the other hand you probably don't need to repeatedly draw the image to a canvas -- if you need the raw data multiple times you probably just want draw to an off screen canvas once and keep that canvas around.

Alas the other problem with canvas is that for security reasons you aren't able to read ImageData from a canvas if you've ever drawn an image (or other resource) from a different origin.

Upvotes: 3

Jeffery To
Jeffery To

Reputation: 11936

You can try doing binary Ajax then decoding the image data manually, but using canvas would be easier.

Upvotes: 0

Related Questions