Omax Tech | Blog | Build an Automated Image Compression Script with Sharp and SVGO

Build an Automated Image Compression Script with Sharp and SVGO

Software Development
August 28, 2026
7-8 min

Share blog

Introduction

Images are usually the heaviest assets on any website. A single uncompressed photo can push several megabytes down the wire, and a handful of them can tank your Largest Contentful Paint (LCP), inflate your Core Web Vitals scores, and slow down first load for visitors on slower connections.

Without a good workflow, compression becomes a manual, forgetful chore designers export, developers upload, and nobody remembers to shrink anything until Lighthouse complains.

In this post, we share the exact workflow we use in our web application development projects: a terminal command that scans every image in the project, finds the heavy ones (over 100 KB), and compresses them automatically using two battle-tested libraries. Sharp for raster images (WebP, PNG, JPEG) and SVGO for SVG files. The best part? It runs in two safe steps so we can preview exactly what will change before touching any file.

Omax Tech | Blog | Figure 1 - The two-step compression workflow: dry run → review → apply.
Figure 1 - The two-step compression workflow: dry run → review → apply.

Why Image Weight Matters

Before we get to commands, it's worth understanding what's at stake.

  • Largest Contentful Paint (LCP): Large hero images are a common cause of slow LCP. If the biggest above-the-fold image is a giant PNG, the browser can't paint until most of it downloads.
  • Bandwidth & cost: Every byte served is bandwidth your visitors pay for - on mobile data, that cost is very real.
  • SEO & Core Web Vitals: Google uses real-world performance (field data) as a ranking factor. Slow pages lose visibility.
  • Repository bloat: Oversized assets slow down clones, builds, and deployments.

Compressing images is one of the cheapest, highest-impact website performance wins available and unlike a lot of “performance work,” it takes minutes, not sprints.

The Tools Behind the Command

Our compression script uses two open-source libraries:

  • Sharp: a high-performance Node.js image processing library that can resize, re-encode, and convert images with near-native speed. We use it for WebP, PNG, and JPEG.
  • SVGO (SVG Optimizer): a tool that strips unnecessary metadata, comments, and redundant path data from SVG files, making them dramatically smaller without changing how they render.

Both are installed as dev dependencies in package.json, so they never ship to production they only run at build/dev time.

The Two-Step Safe Workflow

The whole workflow is designed to be non-destructive by default. We never write over an image until we've seen exactly what will happen.

Step 1 - Dry run (preview only)

bash
npm run compress:images

This scans every image, calculates what it would compress, how much it would save, and prints the results. Nothing is written to disk.

Omax Tech | Blog | Figure 2 - Real dry-run output
Figure 2 - Real dry-run output

Step 2 - Apply

bash
npm run compress:images:apply

Only when we're happy with the preview do we run the apply command, which actually overwrites the files with their optimized versions.

Omax Tech | Blog | Figure 3 - Example apply-run output
Figure 3 - Example apply-run output

Note: The screenshots demonstrate the complete workflow. We first ran the script in DRY RUN mode to safely identify optimization candidates without modifying any files. Once verified, we ran it in APPLY mode to perform the actual compression and reduce image sizes.

This two-step flow prevents surprise changes and lets us review the impact before committing.

How the Script Decides What to Compress

The script (scripts/compress-images.mjs) follows a simple, principled set of rules:

  • 100 KB threshold: Only files larger than 100 KB are processed. Small assets are left alone compressing them wastes time and can even increase size.
  • Max width of 1920px: Any image wider than 1920px is resized down. This covers virtually all real-world display sizes while avoiding pointless giant dimensions.
  • A quality loop: Fresh images often start at quality 82, and the script progressively lowers quality (down to a floor of 55) until the file falls under the threshold. This “try until it fits” approach squeezes out maximum savings while keeping quality acceptable.
  • SVG optimization: For SVG files, SVGO runs in multipass mode with the default preset to strip redundant data.

A quick note on that quality floor: dropping to 55 sounds aggressive, but for web-displayed raster images especially ones rendered at reduced widths in a responsive layout the visible difference is negligible. The eye rarely notices the drop; the network tab absolutely does.

Let's Build Something Great Together

Ready to transform your idea into a powerful software solution? Talk to our experts and get a free consultation.

Contact Us

These rules are configurable, so they scale to any project's needs.

Omax Tech | Blog | Figure 4 - Script decision logic: scan → over 100 KB? → resize → quality loop → SVG via SVGO.
Figure 4 - Script decision logic: scan → over 100 KB? → resize → quality loop → SVG via SVGO.

A simplified look at the core logic

You don't need the full script to understand the idea here's the shape of the quality loop that does the heavy lifting for raster images:

typescript
import sharp from "sharp";
const MAX_WIDTH = 1920;
const SIZE_THRESHOLD = 100 * 1024; // 100 KB
const QUALITY_START = 82;
const QUALITY_FLOOR = 55;
async function compressRaster(inputBuffer, format) {
let quality = QUALITY_START;
let output = inputBuffer;
while (quality >= QUALITY_FLOOR) {
output = await sharp(inputBuffer)
.resize({ width: MAX_WIDTH, withoutEnlargement: true })
.toFormat(format, { quality })
.toBuffer();
if (output.length <= SIZE_THRESHOLD) break;
quality -= 5;
}
return output;
}

The real script wraps this with file-walking, before/after size comparisons, the dry-run/apply flag, and SVGO handling for .svg files but this is the piece doing the actual work.

Understanding the Output

When you run the dry-run command, you get a clean summary:

bash
=== compress-images (DRY RUN) ===
Threshold: >100 KB only | Scanned: 350 images
compressed (✓) 120.2 KB → 44.8 KB images/blog/hero.webp
compressed (✓) 210.5 KB → 71.3 KB images/team/office.jpg
skipped (still large) 340.0 KB → 210.0 KB images/hero/banner.png
--- Summary ---
Candidates (>100 KB): 12
Optimized: 9
Still >100 KB after compress: 3
Saved: 2.35 MB

Each line shows the file path, its size before and after, and whether it's now under 100 KB. The summary tells you how many files qualify, how many got optimized, and critically how many are still over 100 KB, so you know which need a human decision (like a redesign, cropping, or manual optimization).

That “still >100 KB” bucket matters. It's usually images that are already near the quality floor and can't shrink further without visibly degrading a signal to resize the source asset itself, not just re-run the script.

Wiring It Into the Project

Rather than running a long node command every time, we add it as an npm script:

json
"scripts": {
"compress:images": "node scripts/compress-images.mjs",
"compress:images:apply": "node scripts/compress-images.mjs --apply"
}

This makes the workflow a single, memorable command.

We also hook a separate validation script into the prebuild step, so broken or missing image references are caught before a production build:

json
"prebuild": "npm run validate:images"

validate:images (scripts/validate-images.mjs) is a lightweight companion script it doesn't compress anything, it just walks the codebase for <img> tags, next/image calls, and CSS background-image references, then confirms the file each one points to actually exists on disk. It catches typos, renamed files, and stale references before they turn into a broken-image icon in production.

Catching image problems early keeps deployments clean and predictable.

When to Run It

We recommend making compression part of your routine, not an afterthought:

  • After adding new images - before committing.
  • Before every release/build - as part of a quick sanity pass.
  • On a schedule - old repos accumulate heavy assets over time; a periodic run keeps them lean.

You can even wire the apply command into your CI pipeline so every merge automatically shrinks any newly added heavy images for example, as a step that runs compress:images:apply and fails the build if it finds files it can't get under the threshold, forcing a manual look before merge.

Final Words

Fast websites don't happen by accident they happen because the team has a repeatable, low-effort workflow. A single terminal command that finds and compresses heavy images is one of the simplest ways to keep your site fast, your visitors happy, and your performance scores green.

Automate it, run it often, and let your images work for your performance not against it.

If you want to try this on your own project, the pattern above (Sharp for raster + SVGO for SVGs, gated behind a dry-run) drops into almost any Node.js codebase with minimal setup no build tool lock-in required.

Blogs

Discover the latest insights and trends in technology with the Omax Tech Blog.

View All Blogs
Omax Tech | Blog | SaaS MVP Development Cost in 2026-27
10-12 min
November 23, 2026

SaaS MVP Development Cost in 2026-27

How much does a SaaS MVP cost in 2026-27? See price ranges from $15,000 to $100,000+, a stage-by-stage cost breakdown, hidden costs and ways to save.

Read More
Omax Tech | Blog | How to Build a SaaS MVP (Step-by-Step): A Complete Guide for Startups
10-12 min
November 19, 2026

How to Build a SaaS MVP (Step-by-Step): A Complete Guide for Startups

Learn how to build a SaaS MVP in 10 steps: validate the problem, prioritize features, choose a stack, test, launch and measure. Costs and timelines included.

Read More
Omax Tech | Blog | When AI Tests the Software, Who Owns the Quality?
12-15 min
November 11, 2026

When AI Tests the Software, Who Owns the Quality?

AI can execute thousands of tests, but can it own quality? Exploring why quality remains a shared human responsibility even as AI automates testing.

Read More
Omax Tech | Blog | From ETL to ELT: The Evolution of Data Pipelines in Modern Analytics
12-15 min
October 16, 2026

From ETL to ELT: The Evolution of Data Pipelines in Modern Analytics

How and why data pipeline architecture evolved from ETL to ELT.

Read More
Omax Tech | Blog | Bridge View Hybrid: A Smarter Path to Bringing Web Apps to Mobile
8-10 min
October 06, 2026

Bridge View Hybrid: A Smarter Path to Bringing Web Apps to Mobile

Learn how the Bridge View Hybrid architecture uses a React Native shell and WebView to launch iOS and Android apps faster, cheaper, and with less risk.

Read More
Omax Tech | Blog | 10 AI Prompts Every Manual Tester Should Have in Their QA Toolkit
10-12 min
September 30, 2026

10 AI Prompts Every Manual Tester Should Have in Their QA Toolkit

Discover 10 practical AI prompts manual testers can use to improve test coverage, find edge cases, analyze bugs, strengthen regression testing, and become more effective QA engineers.

Read More
Omax Tech | Blog | The Website Accessibility Revolution: Why You Can't Afford to Ignore WCAG 2.2
8-10 min
September 29, 2026

The Website Accessibility Revolution: Why You Can't Afford to Ignore WCAG 2.2

Website accessibility starts with WCAG 2.2. Learn how accessible design, development, QA, and testing can help create websites that work for everyone.

Read More
Omax Tech | Blog | Race Conditions in Web Applications: Why Correct Code Produces Wrong Results
10-12 min
September 21, 2026

Race Conditions in Web Applications: Why Correct Code Produces Wrong Results

Race conditions silently corrupt data when concurrent requests touch shared state at the wrong time. Learn how atomic updates, transactions, idempotency, and locking keep your application correct under real concurrency.

Read More
Omax Tech | Blog | AI Writes the Code • Stop Blindly Shipping It Without Reviewing the Engineering
8-10 min
September 17, 2026

AI Writes the Code • Stop Blindly Shipping It Without Reviewing the Engineering

A practical perspective on AI-generated code, scalability, maintainability, and engineering judgment and why engineering review still owns the final decision.

Read More