Search code examples
javascriptimagefiledata-uri

Convert Link from Image URL from s3 into File Object using JavaScript


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


Solution

  • 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!
    });