Scripts by vojtaholik

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 = env.TINIFY_API_KEY;
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 = "-optimized";
let newFileName = 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;
});
});
});
}

Get your api key on tinify.com/dashboard/api (assuming you're logged in) and add it to ~/.kenv/.env file like so:

# ...
TINIFY_API_KEY=your_key

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}`);
Discuss Post

Slugify selected file names

// Menu: Slugify file name
// Description: Slugify selected files
// Author: Vojta Holik
// Twitter: @vjthlk
let slugify = await npm("slugify")
let selectedFiles = await getSelectedFile()
const filePaths = selectedFiles.split("\n")
for (let filePath of filePaths) {
let originalFileName = path.basename(filePath)
let newFileName = slugify(originalFileName, {
lower: true,
})
let newFilePath = path.join(
path.dirname(filePath),
newFileName
)
cp(filePath, newFilePath)
}
Discuss Post