S
S
Sergey Lyalin2022-03-22 14:44:05
JavaScript
Sergey Lyalin, 2022-03-22 14:44:05

How to create an image from a base64 string?

I crop the images to a small one through the lib. Either returns base64. Even I need to send this case as a file to the server.
I already found questions where people needed to just render, but the question is exactly: how to convert base64 to js to a file?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Lyalin, 2022-03-22
@Spokik

I found this solution

function dataURLtoFile(dataurl, filename) {
      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);
      }
      return new File([u8arr], filename, { type: mime });
    }

N
Nadim Zakirov, 2022-03-22
@zkrvndm

This is simply done in one line via fetch:

blob = await (await fetch('data:image/png;base64,блабла')).blob();

The blob variable will contain a file, it can be safely sent to the server using FormData.

N
Nikolai Savelyev, 2022-03-22
@AgentSmith

what's stopping you from saving base64 to a file?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question