使用JavaScript将链接从s3的图像URL转换为文件对象

时间:2019-02-12 16:01:21

标签: javascript image file data-uri

我想使用JavaScript将s3图像链接转换为文件对象。

我已经找到了如何使用图像URI进行此操作,但无法弄清楚如何将图像URL转换为URI。完成此操作后,我可以将其转换为文件对象

在此处显示图像链接:

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

1 个答案:

答案 0 :(得分: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!
});