DEV Community

Roman Klymenko
Roman Klymenko

Posted on

How to Build a High-Performance Image Optimization Pipeline in 5 Minutes

Images make up over 60% of average web page weight. If you're serving unoptimized, raw JPEGs or PNGs to mobile clients, your site's Largest Contentful Paint (LCP) score is taking a massive hit.

In this quick guide, weโ€™ll show you how to automate image compression using the Pixozip SDK to convert images to AVIF/WebP on the fly.

Why AVIF over traditional JPEG?

Traditional JPEG compression is linear. AVIF uses intra-frame video compression algorithms that analyze texture patterns. This allows AVIF to shrink file sizes by 70-90% compared to legacy JPEG while keeping the same visual clarity.

Step 1: Install the SDK

Install the official Node.js SDK:

npm install @pixozip/sdk
Enter fullscreen mode Exit fullscreen mode

Step 2: Initialize and Compress

Import the library, supply your API key, and call the .shrink() method. It handles error catching, request formatting, and automatic retries with exponential backoff internally:

import { Pixozip } from "@pixozip/sdk";
import * as fs from "fs/promises";

const zip = new Pixozip({ apiKey: "YOUR_API_KEY" });

// Load the image file into a buffer
const imageBuffer = await fs.readFile("./hero_banner.png");

// Compress and convert to AVIF
const result = await zip.shrink(imageBuffer, {
  contentType: "image/png",
  output: "avif",           // Automatically converts png to avif
  qualityTier: "balanced",  // Targets visually lossless quality (SSIM > 0.995)
  resize: { width: 1200 }   // Scales down layout resolutions
});

// Download and write the optimized image
const optimizedBuffer = await result.download();
await fs.writeFile("./hero_banner.opt.avif", optimizedBuffer);

console.log(`Optimized! Saved ${Math.round((1 - (result.ratio ?? 1)) * 100)}% of bytes.`);
console.log(`Download URL: ${result.downloadUrl}`);
Enter fullscreen mode Exit fullscreen mode

Async Operations for High Volume

If you are processing batches of images, blocking your server thread synchronously is not ideal. You can trigger an asynchronous job and receive a webhook callback when it's done:

const job = await zip.shrink(imageBuffer, {
  contentType: "image/jpeg",
  output: "webp",
  async: true // Gateway returns 202 immediately
});

console.log(`Job queued with ID: ${job.jobId}`);
Enter fullscreen mode Exit fullscreen mode

Conclusion

By adding a few lines of code to your upload pipeline, you can drastically decrease bandwidth consumption, reduce AWS S3 storage bills, and improve page speed rankings.

Get a free API key with 500 free optimizations per month at pixozip.

Top comments (0)