DevOps

Automating Image Compression in Your CI/CD Pipeline

Manual image optimization doesn't scale. When multiple developers are pushing changes daily, it's easy for unoptimized images to slip into production. The solution? Automate image compression in your CI/CD pipeline. This guide shows you how.

Why Automate Image Compression?

Automating image optimization in your pipeline provides several benefits:

  • Consistency - Every image gets optimized, every time
  • Developer productivity - No manual optimization steps
  • Quality gates - Block deployments with oversized images
  • Versioning - Track optimization alongside code changes
  • Speed - Parallel processing of multiple images

Choosing Your Approach

There are two main strategies for CI/CD image optimization:

1. Build-Time Optimization

Optimize images during the build process before deployment:

[Push] -> [Build] -> [Optimize Images] -> [Deploy]

Pros:

  • Images optimized before reaching production
  • Can fail builds if optimization fails
  • Works with any hosting

Cons:

  • Increases build time
  • Requires compute resources

2. Pre-Commit Optimization

Optimize images before they enter the repository:

[Optimize] -> [Commit] -> [Push] -> [Build] -> [Deploy]

Pros:

  • Faster builds
  • Smaller repository size
  • Images always optimized in repo

Cons:

  • Requires developer tooling setup
  • Less control over pipeline

The Compress Call

The API answers a compress request with JSON, not with the image. The JSON carries a download_url that works for 24 hours, so every pipeline below makes two requests: compress, then download. They all share one small script. Save it as scripts/optimize-image.sh, make it executable (chmod +x scripts/optimize-image.sh), and keep your API key in an OCTOSQUEEZE_API_KEY secret. It needs curl and jq.

#!/usr/bin/env bash
# Usage: scripts/optimize-image.sh path/to/image.jpg
# Writes path/to/image.webp next to the original.
set -euo pipefail

image="$1"
output="${image%.*}.webp"

response=$(curl -s -X POST https://api.octosqueeze.com/api/v1/compress \
  -H "Authorization: Bearer $OCTOSQUEEZE_API_KEY" \
  -F "file=@$image" \
  -F "format=webp")

url=$(printf '%s' "$response" | jq -r '.data.download_url // empty')

if [ -z "$url" ]; then
  echo "Skipped $image: $(printf '%s' "$response" | jq -r '.error.message // "no file returned"')" >&2
  exit 0
fi

curl -sf -o "$output" "$url"
echo "Optimized: $image -> $output"

File names can contain spaces, so the loops below read one path per line (while IFS= read -r) instead of splitting a list with for image in $(...).

GitHub Actions Implementation

Basic Image Optimization Workflow

Create .github/workflows/optimize-images.yml:

name: Optimize Images

on:
  push:
    paths:
      - '**.jpg'
      - '**.jpeg'
      - '**.png'
      - '**.gif'
      - '**.webp'

permissions:
  contents: write

jobs:
  optimize:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Optimize changed images
        env:
          OCTOSQUEEZE_API_KEY: ${{ secrets.OCTOSQUEEZE_API_KEY }}
        run: |
          BEFORE="${{ github.event.before }}"
          # A new branch's first push has no "before": compare with the parent
          if [ "$BEFORE" = "0000000000000000000000000000000000000000" ]; then BEFORE="HEAD~1"; fi
          git diff --name-only --diff-filter=AM "$BEFORE" ${{ github.sha }} \
            | grep -E '\.(jpe?g|png|gif)$' \
            | while IFS= read -r image; do
                ./scripts/optimize-image.sh "$image"
              done

      - name: Commit optimized images
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git add -A
          git commit -m "chore: optimize images [skip ci]" || exit 0
          git push

Advanced Workflow with Quality Gates

name: Image Quality Gate

on:
  pull_request:
    paths:
      - 'public/images/**'
      - 'assets/images/**'

jobs:
  check-images:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Check image sizes
        run: |
          MAX_SIZE=500000  # 500KB
          FAILED=0

          while IFS= read -r file; do
            SIZE=$(stat -c%s "$file")
            if [ "$SIZE" -gt "$MAX_SIZE" ]; then
              echo "::error file=$file::Image exceeds 500KB limit ($SIZE bytes)"
              FAILED=1
            fi
          done < <(find . -type f \( -name "*.jpg" -o -name "*.png" -o -name "*.webp" \))

          if [ "$FAILED" -eq 1 ]; then
            echo "::error::Some images exceed the size limit. Please optimize them."
            exit 1
          fi

      - name: Verify WebP versions exist
        run: |
          find public/images -type f \( -name "*.jpg" -o -name "*.png" \) | while IFS= read -r image; do
            if [ ! -f "${image%.*}.webp" ]; then
              echo "::warning file=$image::Missing WebP version"
            fi
          done

GitLab CI Implementation

Create .gitlab-ci.yml:

stages:
  - optimize
  - build
  - deploy

optimize-images:
  stage: optimize
  image: alpine:3.20
  rules:
    - changes:
        - "**/*.{jpg,jpeg,png,gif}"
  before_script:
    - apk add --no-cache bash curl jq git
  script:
    - |
      git diff --name-only --diff-filter=AM HEAD~1 | grep -E '\.(jpe?g|png|gif)$' | while IFS= read -r image; do
        ./scripts/optimize-image.sh "$image"
      done
  artifacts:
    paths:
      - public/images/
    expire_in: 1 hour

build:
  stage: build
  dependencies:
    - optimize-images
  script:
    - npm run build

Jenkins Pipeline

Create Jenkinsfile:

pipeline {
    agent any

    environment {
        OCTOSQUEEZE_API_KEY = credentials('octosqueeze-api-key')
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Optimize Images') {
            when {
                anyOf {
                    changeset "**/*.jpg"
                    changeset "**/*.png"
                }
            }
            steps {
                sh '''
                    git diff --name-only --diff-filter=AM HEAD~1 | grep -E '\\.(jpe?g|png)$' | while IFS= read -r image; do
                        ./scripts/optimize-image.sh "$image"
                    done
                '''
            }
        }

        stage('Build') {
            steps {
                sh 'npm run build'
            }
        }
    }
}

Pre-Commit Hook Setup

For local optimization before commits, use a pre-commit hook. It calls the same script, so jq and the OCTOSQUEEZE_API_KEY variable have to be on each developer's machine.

Using Husky (Node.js)

Install Husky:

npm install --save-dev husky
npx husky init

Create .husky/pre-commit:

#!/bin/sh

git diff --cached --name-only --diff-filter=ACM | grep -E '\.(jpe?g|png|gif)$' | while IFS= read -r image; do
    ./scripts/optimize-image.sh "$image"
    # The script skips a file the API could not compress
    if [ -f "${image%.*}.webp" ]; then git add "${image%.*}.webp"; fi
done

Using Git Hooks Directly

Create .git/hooks/pre-commit:

#!/bin/bash

git diff --cached --name-only --diff-filter=ACM | grep -E '\.(jpe?g|png)$' | while IFS= read -r file; do
    ./scripts/optimize-image.sh "$file"
    if [ -f "${file%.*}.webp" ]; then git add "${file%.*}.webp"; fi
done

Parallel Processing for Speed

When dealing with many images, process them in parallel:

Bash Parallel Processing

#!/bin/bash
export OCTOSQUEEZE_API_KEY

# Process 4 images at a time; -print0 / -0 keep paths with spaces intact
find . -type f \( -name "*.jpg" -o -name "*.png" \) -print0 \
    | xargs -0 -P 4 -n 1 ./scripts/optimize-image.sh

Node.js Concurrent Processing

Save as optimize.mjs and run it with Node 18 or later (it uses the built-in fetch):

import { readFile, writeFile } from 'node:fs/promises';
import { basename } from 'node:path';
import { globSync } from 'glob';
import pLimit from 'p-limit';

const limit = pLimit(4); // 4 concurrent requests

async function optimizeImage(path) {
  const form = new FormData();
  form.append('file', new Blob([await readFile(path)]), basename(path));
  form.append('format', 'webp');

  const response = await fetch('https://api.octosqueeze.com/api/v1/compress', {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.OCTOSQUEEZE_API_KEY}` },
    body: form,
  });
  const result = await response.json();

  if (!result.success || !result.data.download_url) {
    console.warn(`Skipped ${path}: ${result.error?.message ?? 'no file returned'}`);
    return;
  }

  const output = path.replace(/\.\w+$/, '.webp');
  const file = await fetch(result.data.download_url);
  await writeFile(output, Buffer.from(await file.arrayBuffer()));
  console.log(`Optimized: ${path} -> ${output}`);
}

const images = globSync('**/*.{jpg,png}', { ignore: ['node_modules/**', 'dist/**'] });
await Promise.all(images.map((image) => limit(() => optimizeImage(image))));

Caching for Faster Builds

Avoid re-optimizing unchanged images:

Content-Addressable Caching

# GitHub Actions with caching
- name: Cache optimized images
  uses: actions/cache@v4
  with:
    path: .image-cache
    key: images-${{ hashFiles('**/*.jpg', '**/*.png') }}
    restore-keys: images-

- name: Optimize uncached images
  run: |
    mkdir -p .image-cache
    find . -path ./.image-cache -prune -o -type f \( -name "*.jpg" -o -name "*.png" \) -print | while IFS= read -r image; do
      HASH=$(md5sum "$image" | cut -d' ' -f1)
      CACHED=".image-cache/${HASH}.webp"

      if [ -f "$CACHED" ]; then
        cp "$CACHED" "${image%.*}.webp"
      else
        ./scripts/optimize-image.sh "$image"
        if [ -f "${image%.*}.webp" ]; then cp "${image%.*}.webp" "$CACHED"; fi
      fi
    done

Monitoring and Alerts

Track optimization results in your pipeline:

- name: Report optimization stats
  run: |
    ORIGINAL_SIZE=$(du -sb original-images | cut -f1)
    OPTIMIZED_SIZE=$(du -sb optimized-images | cut -f1)
    SAVINGS=$((100 - (OPTIMIZED_SIZE * 100 / ORIGINAL_SIZE)))

    echo "## Image Optimization Report" >> $GITHUB_STEP_SUMMARY
    echo "- Original size: $(numfmt --to=iec $ORIGINAL_SIZE)" >> $GITHUB_STEP_SUMMARY
    echo "- Optimized size: $(numfmt --to=iec $OPTIMIZED_SIZE)" >> $GITHUB_STEP_SUMMARY
    echo "- Savings: ${SAVINGS}%" >> $GITHUB_STEP_SUMMARY

Conclusion

Automating image compression in CI/CD ensures:

  1. Consistent optimization across all team members
  2. Quality gates to prevent oversized images in production
  3. Faster development with no manual steps
  4. Reliable deployments with predictable image sizes

Start with a simple workflow that optimizes changed images, then add quality gates and caching as your needs grow.

On this page

Try it on your own images

Ship faster websites with OctoSqueeze.

No credit card required · 500 free images/month