0

I'm trying to create a image from a video by using a canvas and then sending the image to an API.

This is my code (large parts are omitted for brevity)

      var image = new Image();
        image.src = canvas.toDataURL("image/png");

      var newFile = new File([atob(image.src)], lorem.png, {
         type: "image/png",
          lastModified: Date.now()
         })

image.src is a long string that seems to be in the format base64 data:image/png;base64

[Link to the data ][1]:https://gist.github.com/anonymous/d357e780fa60b2c47490a9f795e34acf

When I try to decode the data into binary with the function atob, I get the following error:

Error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

It's not clear to me which part of the base64 data are not formatted correctly.

3 Answers 3

1

You have to cut of the head of the data url. When you put the image into image.src its content is like data:image/png;base64,BASE64ENCODEDSTUFF. Obsviously data:image/png;base64, is not base64 so decoding it with atob will fail.

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

Comments

1

This won't work first, because a data-uri consists of a header then followed by the Base-64 data - atob() can only deal with the Base-64 part. This means you need to cut off the header ("data:image/png;base64,").

But going via Data-URI is slow and wastes more memory than needed. Use a blob directly - this is how:

var img = new Image();

canvas.toBlob(function(blob) {
  var newFile = new File([blob], "lorem.png", {type: "image/png"});
  img.src = (URL || webkitURL).createObjectURL(blob);
  // ...
});

Comments

0

This is my go to solution to convert an Base64 type image to binary file. This can handle other types of files also.

export const dataType64toFile = (dataurl, filename = "NewFile") => {
  //Convert base64 to file
  let arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  let newFile = new File([u8arr], filename, {
    type: mime,
  })
  return newFile
}

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.