Skip to content

About

Command line interface to compress your images with Tinify / TinyPNG

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

tinify

Compress and convert images from the command line, using the Tinify API.

Supports .png, .jpg, .jpeg, .webp, .avif and .jxl.

Install

With npm

You need Node 20.12 or later (on Node 21, 21.7 or later). This works on Windows too:

npm install -g @tinify/cli

Download the binary

The binaries run on macOS and Linux, on arm64 (Apple Silicon) and x64, and on Windows x64. Each release has a binary for every platform: tinify-darwin-arm64 (Apple Silicon Macs), tinify-darwin-x64 (Intel Macs), tinify-linux-arm64, tinify-linux-x64 and tinify-windows-x64.exe, and SHA256SUMS to check them against.

curl -fsSL -o tinify https://github.com/tinify/tinify-cli/releases/latest/download/tinify-darwin-arm64
chmod +x tinify
sudo mv tinify /usr/local/bin/tinify

On macOS, download it with curl as above: the binaries aren't notarized, so macOS refuses to run one downloaded in a browser. xattr -d com.apple.quarantine tinify lifts that.

On Windows, in PowerShell, download it into a folder of its own and add that folder to your PATH:

$dir = "$env:LOCALAPPDATA\Programs\tinify"
New-Item -ItemType Directory -Force $dir | Out-Null
Invoke-WebRequest https://github.com/tinify/tinify-cli/releases/latest/download/tinify-windows-x64.exe -OutFile "$dir\tinify.exe"
[Environment]::SetEnvironmentVariable("Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";$dir", "User")

Then open a new terminal and run tinify --version. The binary isn't signed, so Windows SmartScreen may warn the first time you run it.

Build from source

You need Bun installed. If you don't have it:

curl -fsSL https://bun.sh/install | bash

Then build and install tinify (on Windows, make build gives dist\tinify.exe; move it to a folder on your PATH):

git clone https://github.com/tinify/tinify-cli.git
cd tinify-cli
bun install
make build
sudo mv dist/tinify /usr/local/bin/tinify

Check that it worked:

tinify --version

That prints a version number. If you get command not found, /usr/local/bin is not on your PATH. Either add it, or put the binary somewhere that already is:

mkdir -p ~/.local/bin
mv dist/tinify ~/.local/bin/tinify
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

Get an API key

Create a free key at tinypng.com/developers. It covers 500 compressions per month. tinify register opens that page in your browser, or prints the link when there is no browser to open.

Save it once:

tinify config --key=YOUR_KEY

This writes ~/.config/tinify/config.json (on Windows, %USERPROFILE%\.config\tinify\config.json), readable only by you on Linux and macOS; on Windows, your user profile's own permissions protect it. You only do it once.

Every run checks the key with Tinify before it uploads anything. A wrong key fails straight away, and the check doesn't count as a compression.

To see what a run would do without calling the API at all (no key needed), add --dry-run:

tinify ./images --convert=webp --output=./web --dry-run

It lists each file and where its result would be written.

Compressing images

One image

tinify photo.png

This overwrites photo.png in place. Keep a copy if you need the original: a hard link isn't a copy, and every hard link to the file gets the compressed image too. The result is written into the same file, so it keeps its permissions, owner, group, ACLs and extended attributes. Ctrl-C, closing the terminal or a plain kill stops tinify right away, but an image being written is finished first, so tinify never leaves a half-written image: only kill -9, a power cut at that very moment, or a write that fails partway can, and a failed write says which image may be damaged.

Closing the terminal stops tinify the same way, even under nohup; to keep a long run going after you close the terminal, run it in tmux, screen or with setsid.

On Windows, Ctrl-C and closing the console window stop tinify the same way. Windows has no plain kill: taskkill /F and Stop-Process end tinify at once, as kill -9 does.

If Tinify can't make an image any smaller, it's left as it is, and it doesn't count toward your usage (the API reference: "unless the file cannot be made any smaller").

Several images

tinify logo.png header.jpg icon.webp

Every image in a folder

tinify ./images

Subfolders are included, but a symlink to a folder isn't followed: name that folder too to include it. A symlink to an image is included. Files that aren't a supported image are skipped. So is what isn't yours to compress, even where it's named like an image:

  • hidden files and folders (names starting with ., such as .thumbnails or .git), unless you add --hidden;
  • the system's own files, even with --hidden: ._ files (macOS metadata), the trash (.Trash…, $RECYCLE.BIN, #recycle, @Recycle), NAS thumbnails and snapshots (@eaDir, #snapshot, @Recently-Snapshot), and the __MACOSX, .AppleDouble and System Volume Information folders;
  • installed packages (node_modules) and photo libraries (*.photoslibrary, Lightroom's *.lrdata previews), whose files their apps manage.

A file or folder you name yourself is always included, and --verbose lists what was skipped. A file named twice, or included by overlapping arguments such as ./images ./images/icons, is only compressed once. An --output folder is never compressed, whether it's inside a folder you name or named itself (as tinify ./images/* --output=./images/min does), so a second run doesn't compress its own results again. --output naming the folder itself leaves nothing to compress; plain tinify ./images compresses in place.

Every path you name must exist: if one doesn't, tinify stops before uploading anything. So if ./compressed doesn't exist yet, tinify ./images ./compressed with --output left out doesn't compress ./images in place: it stops and suggests --output=./compressed. If ./compressed does exist, it's just another folder to compress in place.

Running tinify ./images again skips what it already did, before anything is uploaded: see Running tinify again.

Without overwriting the originals

Use --output to write results to a different folder. The originals are left untouched: an image that --output leads back to, because it names the image's own folder or a symlink to it, fails before its upload (leave out --output to compress in place). New files (here, or converted ones next to the original) get the original's permissions, less your umask, as cp gives them.

tinify ./images --output=./compressed

Folder structure is preserved, so images/icons/logo.png becomes compressed/icons/logo.png. With several paths, the folders below the one they share are kept too: tinify one/logo.png two/logo.png --output=out writes out/one/logo.png and out/two/logo.png, and tinify one two --output=out writes out/one/… and out/two/…. An image Tinify can't make any smaller is copied there unchanged, so the folder still gets every image. So is an image tinify already compressed in place (see Running tinify again): it isn't uploaded again, and the summary says how many were copied. Files already in ./compressed are not overwritten: see Existing files and name collisions.

Converting formats

--convert writes a new file next to the original, with the new extension. The original file stays where it is, unless it already has the target format (see below).

tinify photo.png --convert=webp

That gives you photo.png (unchanged) and photo.webp (compressed).

Format Result
best Whichever format comes out smallest
webp WebP
avif AVIF
jxl JPEG XL
jpeg JPEG

A converted JPEG is named .jpg. Converting to the format a file already has (--convert=jpeg on a .jpg or .jpeg, --convert=webp on a .webp, or best when Tinify picks the file's own format) compresses it in place under its own name, like plain tinify. If the result isn't smaller, the original stays as it is.

With best, Tinify compresses to every format it supports and keeps only the smallest, so the extension you get depends on the image. Flat graphics usually land on WebP; photos often land on AVIF or JPEG XL. Don't rely on the output extension being stable across files — read it from the JSON if you need it.

Existing files and name collisions

tinify only ever replaces the image it was given. If a result would land on any other file that already exists, the image is skipped, not failed, and tinify still exits 0. That file could be photo.webp next to photo.png when converting, or compressed/logo.png from an earlier run. Delete the old file to redo it.

Two rules decide what counts as an earlier result:

  • A pair given together. With tinify ./images --convert=webp, if a.png and its a.webp are both inputs, both are skipped: a.png because its result exists, a.webp because it is the result of a.png. The cost: an unrelated photo.webp next to photo.png isn't compressed by --convert=webp.
  • --convert=best. The result's name is only known once Tinify has picked the format, so any image file with the same name (.png, .jpg, .jpeg, .webp, .avif, .jxl) counts as an earlier result. If that file is also an input, tinify uses the record to tell which of the two is the result. When the record doesn't tell, both are skipped as ambiguous, with a warning naming the other file (in JSON, the skipped entry's of): delete the one that is the result, or rename one. The cost: an unrelated logo.png and logo.jpg side by side aren't compressed by --convert=best.

--convert replaces the extension, so two files whose names differ only by extension collide: pic.avif and pic.jxl both want to become pic.webp. tinify refuses to overwrite the first result, reports the second as a failure, and exits 1. Rename one of them, or process them in separate runs.

Existing results and name collisions are caught before the image is uploaded, so they cost no credit, --convert=best included. The one exception is under --convert=best: two inputs that turn out to want the same result are only caught after their uploads, so those credits are spent. Uploads to S3 are not checked, so they replace whatever is at that key.

Convert a whole folder into a new one

tinify ./images --convert=webp --output=./web

Originals stay in ./images. Converted copies land in ./web.

Let Tinify pick the smallest format

tinify ./images --convert=best --output=./web

Resizing

tinify photo.png --resize=800x600
Argument Meaning
--resize=800x600 Fit inside 800x600
--resize=800x Scale to 800px wide, height follows
--resize=x600 Scale to 600px tall, width follows

Pick how the image fills the box with --method:

Method Needs Result
fit both dimensions Fits inside the box, keeps aspect ratio. Default when you give both.
scale one dimension Scales to that dimension. Default when you give one.
cover both dimensions Fills the box and crops the overflow, smart-cropped to the subject.
thumb both dimensions Like cover, but cuts away flat background areas.
tinify avatar.jpg --resize=200x200 --method=thumb

--method only works alongside --resize. Combinations the API would refuse, such as --method=cover with one dimension, are rejected before anything is uploaded.

Combining

Flags stack. Compress a folder, convert to WebP, cap the width, write somewhere new:

tinify ./photos --convert=webp --resize=1200x --output=./web

Running tinify again

Run tinify again on the same images and it skips what it already did, before any upload. An image whose result is already there is skipped (see Existing files and name collisions). An image tinify compressed in place is recognised by a record:

~/.config/tinify/compressed (in your user profile folder on Windows) holds one line per image tinify wrote: the settings (--resize, --convert) and the SHA-256 of the image. It belongs to your user account on this machine, only grows (about 70 bytes per image), and isn't used for S3 output. A dry run reads it and writes nothing.

  • If you delete the record, tinify compresses those images again: it costs credits, and images compressed in place get a second lossy pass.
  • --recompress compresses again what the record lists. Existing results are still skipped.
  • With --output, an image the record lists is copied to the output folder as it is, without an upload: it is the result, and compressing it again would cost a credit and give it a second lossy pass. That holds when the record lists it with this run's settings: made with the same --resize, if you give one, and by --convert=best, if you use it. --convert to another format doesn't use the record: the image is uploaded, unless its result is already there.
  • If you edit an image, it's compressed again, but its existing --output or --convert result is kept: delete it to redo it.
  • Don't point two runs at the same images at once.

Teams and CI

The record is in your home folder, not in the repository, so CI on a fresh machine compresses everything. Compress only what git says changed:

git diff -z --name-only --diff-filter=AM origin/main...HEAD -- '*.png' '*.jpg' | xargs -0 -r tinify --

-z and -0 keep names with spaces or non-ASCII characters whole. -r runs nothing when no image changed (a bare tinify is a usage error). ...HEAD leaves out images changed on main since your branch started.

Uploading to S3

Point --output at an S3 URL and results go straight to the bucket instead of your disk.

export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
export AWS_REGION=eu-west-1          # optional, defaults to us-east-1

tinify ./images --output=s3://my-bucket/assets/

The trailing slash matters. s3://my-bucket/assets/ treats the path as a folder and appends each file's path, keeping subfolders as a folder --output does. Without the slash, the path is one exact key: that works for a single image, and is refused for several, since they would overwrite each other.

With --convert, the key gets the new extension (assets/photo.webp). --convert=best can't upload into a folder, because the extension is only known after converting: pick a format instead.

Tinify checks the keys, the bucket, the region and write permission when it stores the first result, so images are uploaded one at a time until the first one is stored. If Tinify refuses it, the run stops there with Tinify's reason: one credit spent, nothing left in your bucket. Usually the S3 settings are wrong, but the image itself can be the cause too: if the settings are right, rerun without that image. If an upload fails because of the image itself (for example, an unsupported file), tinify reports it and tries the next. The role needs s3:PutObject and s3:PutObjectAcl; no list or delete permission is required.

Your AWS keys are sent to Tinify, which does the upload. Use keys that can only write to this bucket.

A dry run (--dry-run) lists the keys it would write and doesn't need the AWS keys.

Scripting

Output is JSON whenever tinify isn't writing to a terminal, so piping just works:

tinify ./images --output=./out | jq '.results[].output.size'

Force it in a terminal with --json.

The shape is always an object with a results array, unless an error stops tinify before it gets to the images (see below). failures is present only if something failed, skipped only if something was skipped, log only with --verbose, and dryRun only with --dry-run — so .results[] is safe to pipe unconditionally. A result's or a failure's path is the image's full path, so b.png in two folders is two different paths. A result's outputPath is a full path too, even with a relative --output, or an s3:// URL. In a dry run with --convert=best it is null, since Tinify hasn't picked the format yet.

Each entry of skipped has the image's full path, an outputPath (the existing result, the image itself when compressed in place, or the copy with --output; for result-of-input and ambiguous it is the image's own path), and a reason: already-compressed, result-exists, result-of-input or ambiguous. The last two also have of, the path of the other image. results and skipped together cover every image that has a file on disk; a skip never changes the exit code.

A result has unchanged: true when Tinify couldn't make the image any smaller, so it was left as it is (with --output, copied there as it is). Its output.size then equals its input.size.

tinify exits 1 if any file failed, or if the JSON couldn't be written (to a full disk, say), 0 otherwise. A run stopped by Ctrl-C, kill or a closed terminal ends killed by that signal, so the shell reports 130, 143 or 129 (on Windows, those numbers are the exit code). An error before tinify gets to the images, such as a usage error, a path you named that doesn't exist, a missing or rejected key, no image found, or an unusable --output, writes no JSON: it prints tinify: and the reason on stderr, and exits 1. A folder tinify can't read is a failure: it's listed in failures (can't read this folder (EACCES)), the rest of the run carries on, and tinify exits 1. If that leaves no image at all, it is an error before the images, with no JSON. A broken symlink inside a folder is only a warning. A broken image doesn't stop the rest of the run: it's reported, and the other files still compress. Results are listed in the order the files were given.

Some errors would hit every remaining file, such as an invalid key, a monthly limit that has run out, or a full disk. Those stop the run. An --output folder that is a file, or that you can't write to, is refused before anything is uploaded. An in-place result is written into the image itself, so it needs no access to the folder. A folder that a new result goes into (with --convert, or a subfolder of --output) but that you can't add files to fails only the images going there, before they are uploaded; the rest of the run carries on. A failure whose message starts with not processed: had no result written, so a script can tell which files to retry. Those files were never sent, except when Ctrl-C or kill stopped one during its upload: that one says not processed: interrupted during its upload, may have used a credit, and with an S3 --output may have been stored.

All options

Option Effect
--convert=FORMAT Convert to best, webp, avif, jxl or jpeg
--resize=WxH Resize. Also Wx or xH
--method=METHOD fit, scale, cover, or thumb. Requires --resize
--output=PATH Write to a folder, or to s3://bucket/path/
--recompress Compress images tinify already compressed again
--hidden Include hidden files and folders when walking a folder
--concurrency=N Compress N images at once. Default 2
--dry-run List what would happen. No API call, no key needed
-- Treat everything after it as a file name
--json Force JSON output
--no-progress Hide the progress bar
--verbose, -v Show each step as it happens, without the progress bar
--version, -V Print the version (or tinify version)
--help, -h Print usage

API key resolution

tinify takes the first key it finds:

  1. TINIFY_API_KEY environment variable
  2. ~/.config/tinify/config.json, written by tinify config --key=

Use the environment variable in CI:

TINIFY_API_KEY=... tinify ./images --output=./out

Files tinify keeps

Besides the images it writes, tinify keeps two files, in ~/.config/tinify/ on Linux and macOS and in %USERPROFILE%\.config\tinify\ on Windows. The folder is always in your home folder: XDG_CONFIG_HOME isn't used.

File What it holds
config.json The API key saved by tinify config --key=. On Linux and macOS, the folder and the file are readable only by you; on Windows, your user profile's own permissions protect them. Not written when you use TINIFY_API_KEY.
compressed The record of the images tinify wrote: one line per image, with the settings and the image's SHA-256, never its name or contents. Only ever grows.

There is no other cache or log. To forget what tinify compressed, delete compressed. To remove everything tinify keeps, key included, delete the folder.

Development

bun install
bun test              # unit tests, and e2e tests that build and run the CLI against a fake API
bun run test:integration  # the npm package against the real API (needs TINIFY_KEY)
bun run typecheck     # tsc --noEmit
bun run lint          # oxlint
bun run format        # oxfmt (format:check to verify only)
make check            # typecheck, lint, format:check and bun test, as CI runs them
make build            # binary at dist/tinify
make release          # macOS, Linux and Windows binaries and SHA256SUMS; run on macOS (needs codesign)
make npm              # npm package: dist/tinify.mjs for Node, and its tarball in dist/npm

The npm package is src/ built into one JavaScript file that runs on Node, so src/ can't use Bun-only APIs (Bun.*, bun:* imports). Tests can use Bun's APIs. Its dependencies aren't in that file: npm installs them, from dependencies in package.json. The binaries have them built in.

The e2e tests (tests/e2e/) run make build and make npm, install the npm package from its tarball into dist/e2e npm/, and run both the package (on Node) and the Bun binary as a user would: every command, error and dry run, real compressing, converting and resizing, with folder trees that differ per OS, and, on Linux and macOS, stopping with a signal. CI runs them on Linux, macOS and Windows. They need make, Node 20.12 or later, npm and access to the npm registry (for the package's dependencies), and they leave their builds in dist/.

They don't call the Tinify API. They start a fake one on 127.0.0.1 and point the CLI at it with the TINIFY_API_ENDPOINT environment variable. The fake serves HTTPS with a test-only certificate (tests/e2e/fixtures/), which the CLI trusts because the tests pass it in NODE_EXTRA_CA_CERTS. TINIFY_API_ENDPOINT must be an https:// URL; it's meant for tests, not for users.

The integration tests (tests/integration.ts) run the npm package, and the Bun binary where it matters, against the real Tinify API: compressing, converting, resizing, a wrong key, an unusable --output, an S3 store that Tinify refuses, and Ctrl-C or kill during a run. Put a key in .env as TINIFY_KEY=... (Bun reads it; git ignores it). A run spends 14 to 20 compressions (a resize or a conversion is billed as one more, and each of the 3 stop tests uploads 2 to 4 images before tinify stops), so bun test leaves them out. CI runs them on every push to main, with the key from the TINIFY_KEY repository secret.

Releasing

Releases are cut by release-please, which reads the commit messages on main, so they follow Conventional Commits. When you squash-merge, that's the PR title.

Commit Next version
fix: ... patch: 1.0.0 → 1.0.1
feat: ... minor: 1.0.0 → 1.1.0
feat!: ..., or a BREAKING CHANGE: footer major: 1.0.0 → 2.0.0
docs:, chore:, ci:, test:, refactor:, build: no release

On every push to main, the Release workflow keeps a release PR open with the next version and its CHANGELOG entry. Merging it tags the release, attaches the binaries to the GitHub Release, and publishes @tinify/cli to npm.

Every push to main that doesn't cut a release replaces the unstable pre-release with the binaries and the npm package of that commit, versioned <last release>-dev+<commit>, so a fix can be tried before it's released. These builds never go to npm.

If uploading or publishing a release fails, run the Release workflow by hand with the release's tag. It skips what's already published.

License

MIT, see LICENSE.

About

Command line interface to compress your images with Tinify / TinyPNG

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages