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?

  • Have you seen this one, there are different ways to convert image to base64. [Link](https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript) – Sameer Jan 27 '20 at 04: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 :) – Ananda Rizki Jan 27 '20 at 04:29

3 Answers3

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>
Rkv88 - Kanyan
  • 1,332
  • 2
  • 7
  • 15
  • 1
    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) – Ananda Rizki Jan 27 '20 at 04:33
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.

ankitkanojia
  • 3,072
  • 4
  • 22
  • 35
Makwana Prahlad
  • 1,025
  • 5
  • 20
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?

Aggestor
  • 110
  • 1
  • 6
Mustafa Omar
  • 399
  • 4
  • 15