Home > database >  how to convert image src url to blob
how to convert image src url to blob

Time:08-26

I wanted to convert an image to blob url I currently can do it if user uploads the image through an input tag but what I want is what if I had a src url for the image how can I get that image then convert that image to blob. Thanks in advance.

EDIT: Someone suggested a similar question, I tried to apply a similar method but I am not getting a blob url back I have updated my code to show the following.

Suggested SO URL: convert image into blob using javascript

//this works for when image is uploaded through an input tag
const image_input = document.querySelector("#image_input");
image_input.addEventListener("change", function() {
  const reader = new FileReader();
  reader.addEventListener("load", () => {
    const uploaded_image = reader.result;
    console.log(uploaded_image)
  });
  reader.readAsDataURL(this.files[0]);
});

//Suggested Method

function loadXHR(url) {

  return new Promise(function(resolve, reject) {
    try {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.responseType = "blob";
      xhr.onerror = function() {
        reject("Network error.")
      };
      xhr.onload = function() {
        if (xhr.status === 200) {
          resolve(xhr.response)
        } else {
          reject("Loading error:"   xhr.statusText)
        }
      };
      xhr.send();
    } catch (err) {
      reject(err.message)
    }
  });
}

//I want to get the image throught a src link the convert that to blob url
//somthing like this
//convert src to blob
//console.log(blobUrl)

const src = '../img/myImage.jpg'
loadXHR(src).then(function(blob) {
  //I currently only get back an object with size and and type not the blob url     it self
  console.log(blob)
});
<input type="file" title="" id="image_input">

CodePudding user response:

Try this way.

const src = '../img/myImage.jpg'
loadXHR(src).then(function(blob) {
    // Here blob is object, you need to convert it to base64 by using FileReader
    const reader = new FileReader();
    reader.addEventListener("load", () => {
        const uploaded_image = reader.result;
        console.log(uploaded_image);
    });
    reader.readAsDataURL(blob);
});

CodePudding user response:

const src = '../img/myImage.jpg'
const toDataURL = url => fetch(url)
  .then(response => response.blob())
  .then(blob => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  }))
toDataURL(src)
  .then(dataUrl => {
    console.log(dataUrl)
  })

  • Related