Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

publicly hosted image with a liberal CORS policy? [closed]

People also ask

Are images affected by CORS?

HTML provides a crossorigin attribute for images that, in combination with an appropriate CORS header, allows images defined by the <img> element that are loaded from foreign origins to be used in a <canvas> as if they had been loaded from the current origin.

What is a CORS issue?

The CORS behavior, commonly termed as CORS error, is a mechanism to restrict users from accessing shared resources. This is not an error but a security measure to secure users or the website which you are accessing from a potential security bleach.

Which property of the image tag allow images from third party sites that allow cross origin access to be reused with canvas?

The crossorigin attribute is a CORS settings attribute. Its purpose is to allow images from third-party sites that allow cross-origin access to be used with canvas .


I usually use http://imgur.com/ for images (same site as SO uses for their inline images) - no sign up required, just upload or paste in an image link and you're ready to go.

It support CORS requirement so you can link directly and use it with canvas for pixel extraction.

If you need to host different files in addition to image I would suggest DropBox as markE does.

There are restriction however, as with any free service incl. ImgUr and DropBox, so be sure to read the Terms (ToS) of use before using the links (ie. none of them intent to function as a CDN so you might want to check out some commercial CDN providers).

Enabling CORS usage

If allowed you can do this in JavaScript - set crossOrigin before setting src:

var img = new Image();
img.crossOrigin = "";  // or "anonymous", will be interpreted the same
...
img.src = "...";

As attribute for HTML tag (order doesn't matter):

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

Test

var img = new Image();
img.crossOrigin = "";
img.onload = test;
img.src = "https://i.imgur.com/fHyEMsl.jpg";

function test() {

  var ctx = document.querySelector("canvas").getContext("2d");
  ctx.drawImage(this, 0, 0);
  
  // This will fail if no CORS support, otherwise all OK
  try {
    ctx.getImageData(0, 0, 10, 10);
    alert("All OK");
  } 
  catch(err) {
    alert("No CORS support...");
  }
}
<canvas></canvas>