Touffy / client-zip

A client-side streaming ZIP generator

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add canvas image to zip

rashid-naico opened this issue · comments

I have canvas with image, converted to dataURL()

const img = document.getElementById("canvas_output").toDataURL();

const blob = await downloadZip([ img ]).blob();

this gives me error

I hope so. A string is not a valid input type for client-zip. You can include the string as the "input" property of a valid input object, or (better) get a Blob or ArrayBuffer from the canvas instead of a data URL, that would be more efficient.

It worked @Touffy

const img = document.getElementById("canvas_output").toDataURL();
// added fetch call
const filedata = await fetch(img );
const file={ name: 'myfile.jpg', input: filedata }
const blob = await downloadZip([ file ]).blob();

Yeah, it worked but it's a bit convoluted. A Blob is definitely the way to go here. Use the canvas.toBlob() method to get the data directly without going through a long URL. And be careful with the filename you use. By default, toBlob() and toDataURL() will produce a PNG, not a JPEG (but you can configure that).

Just to be clear, this is your code, modified to use toBlob() and configured to actually output JPEG instead of PNG (so the filename is consistent):

(edit: sorry, the toBlob method is a bit unorthodox in that it uses a callback instead of returning a value or Promise)

const filedata = await new Promise(resolve => document.getElementById("canvas_output").toBlob(resolve, 'image/jpeg'));
const file={ name: 'myfile.jpg', input: filedata }
const blob = await downloadZip([ file ]).blob();