Skip to content

Instantly share code, notes, and snippets.

@Mamboleoo
Last active March 12, 2024 23:08
Show Gist options
  • Save Mamboleoo/c4180ce4e91846cc5f92ab1ccd0b130d to your computer and use it in GitHub Desktop.
Save Mamboleoo/c4180ce4e91846cc5f92ab1ccd0b130d to your computer and use it in GitHub Desktop.
async function getZipImages(data) {
const zip = new JSZip();
let allImagesPromises = data.bytes.flatMap((bytes, i) => {
// Generate an url from the layer bytes
const url = URL.createObjectURL(new Blob([bytes]))
// Create an image from the url
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(img)
img.onerror = () => reject()
img.src = url;
});
});
let allImages = await Promise.all(allImagesPromises);
allImages.forEach((image, i) => {
// Create a canvas & draw the image in it
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0);
// Remove the Base64 data in the data URL
let dataURL = canvas.toDataURL(`image/${format}`, parseInt(elQuality.value) / 100);
dataURL = dataURL.replace(/^data:image\/(png|jpeg);base64,/, '');
// Add the image to the zip file
zip.file(`${data.names[i]}.${format === 'png' ? 'png' : 'jpg'}`, dataURL, {
base64: true
});
});
zip.generateAsync({
type: 'blob'
}).then(function(content) {
// Create a downloadable link
const link = document.createElement('a');
// Convert the canvas into data URL
link.href = window.URL.createObjectURL(content);
// Set the file name from the selected layer in Figma
link.download = 'images.zip';
// Trigger the link so it downloads the file
link.click();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment