How to download image file from cross domain

Cross Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

<input id="download" type="button" value="download image" />
<script>
var url="https://www.webinovers.com/images/logo.png";
var canvas = document.getElementById("canvas");
var origin = document.getElementById("origin");
var ctx = canvas.getContext("2d");
var src;
var img_obj = new Image();

function crossOrigin(url) {
  var co = "https://api.codetabs.com/v1/proxy?quest=";
  src = co + url;
  img_obj.crossOrigin = 'anonymous';
  img_obj.onload = function() { ; }
  img_obj.src = src;
  
}

function scaleCanvasImage() {
  var imgWidth = img_obj.width;
  var imgHeight = img_obj.height;
  var scaleX = 1;
  var scaleY = 1;
  if (imgWidth > canvas.width) scaleX = canvas.width / imgWidth;
  if (imgHeight > canvas.height) scaleY = canvas.height / imgHeight;
  var scale = scaleY;
  if (scaleX < scaleY) scale = scaleX;
  if (scale < 1) {
    imgHeight = imgHeight * scale;
    imgWidth = imgWidth * scale;
  }
  var dx = (canvas.width - imgWidth) / 2;
  var dy = (canvas.height - imgHeight) / 2;
    
  ctx.beginPath();
  ctx.rect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "white";
  ctx.fill();
  
  ctx.drawImage(img_obj, 0, 0, img_obj.width, img_obj.height, dx, dy, imgWidth, imgHeight);
}

function downloadCanvasImage(filename) {
  var lnk = document.createElement('a'), e;  // create an "off-screen" anchor tag
  lnk.download = filename; // the key here is to set the download attribute of the a tag
  lnk.href = canvas.toDataURL("image/jpeg");
  if (document.createEvent) { // create a "fake" click-event to trigger the download
    e = document.createEvent("MouseEvents");
    e.initMouseEvent("click", true, true, window,
                     0, 0, 0, 0, 0, false, false, false,
                     false, 0, null);

    lnk.dispatchEvent(e);
  } else if (lnk.fireEvent) {
    lnk.fireEvent("onclick");
  }
}

scale.addEventListener("click", function() {scaleCanvasImage();});
download.addEventListener("click", function() {downloadCanvasImage("myimage.jpg");});

window.onload = function() {
  origin.src=url;
  crossOrigin("https://www.webinovers.com/images/logo.png");
}
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *