5

Possible Duplicate:
How to convert an image object to a binary blob

I am facing same-origin policy restrictions when loading remote images. However DOM 0 Image object can be used to load a remote resource (this is essentially the same as creating an <img /> tag).

var fr = new FileReader(),
    img = new Image();

img.src = 'http://distilleryimage8.s3.amazonaws.com/6cf25568491a11e2af8422000a9e28e9_7.jpg';

img.onload = function () {
    // how to get this image as a Blob object?
};

Is there a way to read this resource into a Blob/arraybuffer object? This is not a duplicate of How to convert an image object to a binary blob as the latter does not rise with same-origin issues.

Community
  • 1
  • 1
Gajus
  • 69,002
  • 70
  • 275
  • 438
  • You can put the image on a canvas, then read the canvas as a blob. I think. I'm not sure how to use canvas, but I think you can do that. – gen_Eric Dec 18 '12 at 16:48
  • That actually sounds plausible! Will try it and post an update if it works. – Gajus Dec 18 '12 at 16:50
  • Go for it. Good luck! :-D – gen_Eric Dec 18 '12 at 16:52
  • 1
    @RocketHazmat just saw your comment. I have the same answer but unfortunately it doesn't work. In the canvas element you have same-origin restriction too, so you cant export the canvas to binary/data url if you've drawn remote image over it... – Minko Gechev Dec 18 '12 at 17:11
  • @MinkoGechev: Darn. Oh well, that was all I could think of. – gen_Eric Dec 18 '12 at 17:11
  • You could use a server-side language, like PHP to proxy the image, so that it's "local". – gen_Eric Dec 18 '12 at 17:15
  • @RocketHazmat proxy is not an option as the purpose of the script is exactly to reduce the server-side bandwidth. – Gajus Dec 18 '12 at 17:19
  • @GajusKuizinas: I think you may be out of options then. – gen_Eric Dec 18 '12 at 17:23
  • Related: http://stackoverflow.com/questions/9519386/is-there-any-way-to-save-a-dirty-canvas – apsillers Dec 18 '12 at 17:34
  • Also related (with a potential solution using CORS): http://stackoverflow.com/questions/4672643/html5-canvas-getimagedata-and-same-origin-policy – apsillers Dec 18 '12 at 17:34
  • @apsillers as I have mentioned before, this scenario is dealing with the case where there is no control over the remote content. – Gajus Dec 19 '12 at 10:58

1 Answers1

2

In my opinion it can be accomplished without much pain...

You just need one more HTML5 element. When using canvas you can draw the remote image on it. After that getting the image dataUrl is quite easy, you have such function from the canvas's API. The next step is to use FileReader's readAsDataURL method.

I haven't tried it but theoretically it should work.

  • Edit: It won't work. If the image is from different origin you can't use canvas's toDataURL method. So I don't think there's any solution without server-side.
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68