Skip to content

Instantly share code, notes, and snippets.

@tancredi
Created July 18, 2022 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tancredi/bcffc8aa697b5d12ed0951fe5ddf3d2d to your computer and use it in GitHub Desktop.
Save tancredi/bcffc8aa697b5d12ed0951fe5ddf3d2d to your computer and use it in GitHub Desktop.
Downsize retina assets (Node.js) script
#!/usr/bin/env node
/* eslint-disable @typescript-eslint/no-var-requires */
const { join, basename, dirname } = require('path');
const Jimp = require('jimp');
const glob = require('fast-glob');
const color = require('cli-color');
const BASE_DIRS = ['public'];
const EXTENSIONS = ['png', 'jpeg', 'jpg', 'gif'];
const TARGET_SUFFIX = '@2x';
const SCALE_AMOUNT = 0.5;
/**
* Downsize retina assets script
*
* Recursively look for all retina assets (suffixed with @2x) and generate
* scaled down versions
*/
const downsize = async filename => {
console.log(color.blue(`Downsizing ${color.cyan(filename)}…`));
const outPath = join(
dirname(filename),
basename(filename).replaceAll(TARGET_SUFFIX, '')
);
const image = await Jimp.read(filename);
image.scale(SCALE_AMOUNT);
await image.writeAsync(outPath);
console.log(`${color.green('✓')} Saved resized to ${outPath}`);
};
const run = async () => {
const files = await glob(
`./(${BASE_DIRS.join('|')})/**/*${TARGET_SUFFIX}.(${EXTENSIONS.join('|')})`
);
await Promise.all(files.map(downsize));
};
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment