简体   繁体   中英

javascript how to save base64 data as png

I am using the getDirectoryHandle and getFileHandle APIs. I want to save a picture in the specified directory. I have the base64 data of the picture, but I don't know how to save the base64 as a picture

const hDir = await showDirectoryPicker();
const hImageFile = await hDir.getFileHandle("test.png", {
  create: true,
});
const w$ = await hImageFile.createWritable();
await w$.write( canvas.toDataURL('image/png') );
await w$.close();

I tried:

await w$.write( atob(canvas.toDataURL('image/png')) );

but the saved picture is not recognized.

It seems you just miss some code.

Under Chrome console, you can print the DataURL of

canvas.toDataURL('image/png')

and you will see it begins with

data:image/png;base64,

This is the header of DataURL, not the header of image file. So we need to remove it, by ignore the 22 charactors

canvas.toDataURL('image/png').substring(22)

and then turn the string contents into byte array

function _base64ToArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

finally, replace

await w$.write( atob(canvas.toDataURL('image/png')) );

with

await w$.write( _base64ToArrayBuffer(canvas.toDataURL('image/png').substring(22)));

enjoy.

canvas.toBlob(async function (blob) {
  const w$ = await hImageFile.createWritable();
  await w$.write(blob);
  await w$.close();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM