Skip to content

Instantly share code, notes, and snippets.

@vojtaholik
Created March 9, 2023 16:11
Show Gist options
  • Save vojtaholik/668956485c13cd9c08c9c877c47a1ded to your computer and use it in GitHub Desktop.
Save vojtaholik/668956485c13cd9c08c9c877c47a1ded to your computer and use it in GitHub Desktop.
// Menu: Tinify
// Description: Compress selected images with Tinify
// Author: Vojta Holik
// Twitter: @vjthlk
let tinify = await npm("tinify");
let fs = await import("fs");
let selectedFiles = await getSelectedFile();
tinify.key = await env("TINIFY_API_KEY", {
hint: md("get your Tinify api key at https://tinypng.com/developers"),
ignoreBlur: true,
secret: true,
});
let filePaths = selectedFiles.split("\n");
for (let filePath of filePaths) {
let directory = path.dirname(filePath);
let extension = path.extname(filePath);
let originalFileName = path.basename(filePath);
let suffix = "";
// let newFileName = originalFileName.replace(extension, suffix + extension);
let isHD = originalFileName.includes("@2x");
let newFileName = isHD
? originalFileName
.replace("@2x", "")
.replace(extension, `${suffix}@2x${extension}`)
: originalFileName.replace(extension, `${suffix}${extension}`);
fs.readFile(filePath, (err, sourceData) => {
if (err) throw err;
tinify.fromBuffer(sourceData).toBuffer((err, resultData) => {
if (err) throw err;
fs.writeFile(`${directory}/` + newFileName, resultData, (err) => {
if (err) throw err;
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment