0

Let say I have an image tag in my page:

<img src="https://i.picsum.photos/id/949/200/300.jpg" alt="foo" />
  • The src path is an absolute path address and not a data URI
  • The src path could be from other site (CORS)

How to download that image and convert File object or binary file in vanilla JavaScript without having CORS issue?

2
  • Have you seen this one, there are different ways to convert image to base64. Link Commented Jan 27, 2020 at 4:01
  • Hey @SameerKhan thanks for the link, but I think those ways are to convert image to base64. My case is converting url to image :) Commented Jan 27, 2020 at 4:29

3 Answers 3

0

you can convert to base64 or using blob

jQuery.ajax({
        url: 'https://i.picsum.photos/id/949/200/300.jpg',
        xhrFields:{
            responseType: 'blob'
        },
        success: function(data){            
            var blobData = data;
            var url = window.URL || window.webkitURL;
            var src = url.createObjectURL(data);
            $('#img').attr("src", src);
        }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
<img id='img'>
</body>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. But this is not what I'm looking for, I'm looking the way to convert url to image File object / Blob instead object url. I guess my questions is not clear enough (going to edit it)
0

Please try this code to convert the image source path to file object:

function getDataUri(url, callback)
{
    var image = new Image();
    image.onload = function () {
        var canvas = document.createElement('canvas');
        canvas.width = this.naturalWidth; 
        canvas.height = this.naturalHeight;
        canvas.getContext('2d').drawImage(this, 0, 0);       
       callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));
        callback(canvas.toDataURL('image/png'));
   };

   image.src = url;
}

getDataUri('/logo.png', function(dataUri) {

});

I hope the above code will be useful for you.

Comments

0

I think the answer to your question is here.

Read /Process image through javascript by passing its URL - Similar to file_get_contents in PHP?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.