Frage

Suppose we have the HTML page with some JPEG images being served from external domains. The goal is to analyze some color data of that images using JavaScript.

The common approach to this problem is to "convert" image to HTML canvas and access color data (see https://stackoverflow.com/a/8751659/581204):

var img = $('#my-image')[0];
var canvas = $('<canvas/>')[0];
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

var pixelInfo = canvas.getContext('2d').getImageData(xOffset, yOffset, 1, 1).data;

But this technique would not work with externally loaded images as trying to access canvas data with external image will raise the security error:

SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

Is there any other way to access color data for external images or this is a dead end?

War es hilfreich?

Lösung

You can set up a page proxy on your own server.

Diagram

A page proxy is simply a page which fetches the image on the url you want to retrieve to server, then forwards it to you from that page instead. This way the image becomes part of the same origin as the script is running on.

This will work for PHP, .Net, cgi etc. but you would to make the page and its code. You will most likely find plenty of examples for this out there (google it for your specific platform).

If you don't have access to do this then there are only these options left:

  • Move/copy the image manually to your page's origin
  • Request CORS usage (which require server to have this enabled)
  • If server doesn't, ask the owner kindly to enable this for your domain and then do CORS request

A CORS request is done by specifying either the attribute in an image's tag:

<img src="..." crossOrigin="anonymous">

or property in JavaScript:

 var img = new Image;
 img.onload  = ...
 img.crossOrigin = '';
 img.src = '...';
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top