0

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.

2
  • is this on nodeJS? are you able to use fs module? Commented Nov 20, 2020 at 3:54
  • @lanxion Chrome 87, not in nodejs environment Commented Nov 20, 2020 at 4:10

2 Answers 2

1

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.

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.