Compress selected images with Tinify

tinify

// 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 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;
});
});
});
}

You can change file names and directory to best suite your workflow. Since I often work with @2x images I adjusted the script to correctly suffix that part.
let isHD = originalFileName.includes("@2x");
let newFileName = isHD
? originalFileName
.replace("@2x", "")
.replace(extension, `${suffix}@2x${extension}`)
: originalFileName.replace(extension, `${suffix}${extension}`);