Skip to content

Instantly share code, notes, and snippets.

@dexit
Created January 7, 2025 17:10
Show Gist options
  • Save dexit/848f50bd28df5c613caea15ef6f950a1 to your computer and use it in GitHub Desktop.
Save dexit/848f50bd28df5c613caea15ef6f950a1 to your computer and use it in GitHub Desktop.
Extract images from website using css selector output as zip file and control the output format and extension webp or jpg and quality
function downloadImagesAsZip(className) {
const zip = new JSZip();
const imgFolder = zip.folder("images");
const images = document.querySelectorAll(".team-member-photo img");
const imagePromises = Array.from(images).map(async (img, index) => {
const src = img.getAttribute('src');
if (src) {
try {
const response = await fetch(src);
const blob = await response.blob();
const imageBitmap = await createImageBitmap(blob);
const canvas = document.createElement('canvas');
canvas.width = imageBitmap.width;
canvas.height = imageBitmap.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(imageBitmap, 0, 0);
// Choose desired output format (jpeg or webp)
const outputFormat = 'image/jpeg'; // or 'image/webp'
// Correctly set file extension based on outputFormat
const fileExtension = outputFormat === 'image/jpeg' ? 'jpg' : 'webp'; //Simplified conditional statement
const fileName = `image-${index + 1}.${fileExtension}`;
const convertedBlob = await new Promise(resolve => canvas.toBlob(resolve, outputFormat, outputFormat === 'image/jpeg'? 0.99 : undefined)); //Added quality parameter for jpg
imgFolder.file(fileName, convertedBlob);
} catch (error) {
console.error("Error processing image:", error);
}
}
});
Promise.all(imagePromises)
.then(() => {
zip.generateAsync({ type: "blob" })
.then(content => saveAs(content, "images.zip"));
});
}
// Ensure JSZip and FileSaver are loaded before calling this function
downloadImagesAsZip('.team-member-photo img');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment