1

I want to convert my s3 image link into a file object using JavaScript.

I've found out how to do this with an image URI but wasn't able to figure out how to convert the image URL into a URI. Once I do this I could convert it into a file object

Heres the image link:

http://s3.us-east-2.amazonaws.com/rentpop/298%2F2014-mclaren-650s-Spyder-Tarocco-Orange-2.jpg

Yosef Yomtobian
  • 92
  • 1
  • 10

1 Answers1

0

Source for this code

function getDataUri(url, callback) {
    var image = new Image();

    image.onload = function () {
        var canvas = document.createElement('canvas');
        canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
        canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size

        canvas.getContext('2d').drawImage(this, 0, 0);

        // Get raw image data
        callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));

        // ... or get as Data URI
        callback(canvas.toDataURL('image/png'));
    };

    image.src = url;
}

// Usage
getDataUri('local_location_to_image.extension', function(dataUri) {
    // Do whatever you'd like with the Data URI!
});
Santhosh Kumar
  • 543
  • 8
  • 22
  • I inputted this into the console and got an error. Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. at Image.image.onload (:12:25) – Yosef Yomtobian Feb 12 '19 at 16:11
  • may be due to cross-origin security issue, try to download and use the image in local location instead of remote location – Santhosh Kumar Feb 12 '19 at 16:13
  • I believe your right. When i tried add Anonymous as crossOrigin for the image i get this error Access to image at 'http://s3.us-east-2.amazonaws.com/rentpop/298%2F2014-mclaren-650s-Spyder-Tarocco-Orange-2.jpg' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. – Yosef Yomtobian Feb 12 '19 at 16:17
  • Would you know a way around this? – Yosef Yomtobian Feb 12 '19 at 16:18
  • can you check with this ? https://stackoverflow.com/questions/17533888/s3-access-control-allow-origin-header – Santhosh Kumar Feb 12 '19 at 16:28