Created
December 27, 2023 15:48
-
-
Save davidsneal/ac81ac8d9fa98d76a296f968174a48ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Name: convert selected images | |
import "@johnlindquist/kit"; | |
// Grab selected files | |
const files = (await getSelectedFile()).split("\n"); | |
// Set up whitelist of formats | |
const supportedFormats = [".heic", ".png", ".gif", ".webp", ".jpg", ".jpeg"]; | |
// Filter files based on supported formats | |
const selectedFiles = files.filter(file => | |
supportedFormats.some(format => file.toLowerCase().endsWith(format)) | |
); | |
// Notify if no files are selected | |
if (!selectedFiles.length) { | |
await notify("No supported files selected"); | |
exit(); | |
} | |
const convertHeic = await npm("heic-convert"); | |
const sharp = await npm("sharp"); | |
const getUniquePath = async (outputPath, suffix = "") => { | |
if (await isFile(outputPath)) { | |
const name = path.basename(outputPath, path.extname(outputPath)); | |
const newName = `${name}${suffix}-copy${path.extname(outputPath)}`; | |
const newPath = path.join(path.dirname(outputPath), newName); | |
return await getUniquePath(newPath, `${suffix}-copy`); | |
} else { | |
return outputPath; | |
} | |
}; | |
// Convert selected files to the chosen output format using appropriate libraries | |
for (const file of selectedFiles) { | |
const content = await readFile(file); | |
const name = path.basename(file).split(".")[0]; | |
const outputPath = path.join(path.dirname(file), `${name}.jpg`); | |
const uniqueOutputPath = await getUniquePath(outputPath); | |
if (file.toLowerCase().endsWith(".heic")) { | |
const outputBuffer = await convertHeic({ | |
buffer: content, | |
format: 'JPEG', | |
quality: 0.5, | |
}); | |
await writeFile(uniqueOutputPath, outputBuffer); | |
} else { | |
const sharpImage = sharp(content); | |
await sharpImage.jpeg({ quality: 40 }).toFile(uniqueOutputPath); | |
} | |
} | |
await notify(`Converted selected files to jpg`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment