Last updated: February 5, 2025

<span aria-hidden="true" id="automating-jpeg-optimization-with-jpegoptim-in-your-projects"></span>

# Automating JPEG optimization with jpegoptim in your projects

![Kevin van Zonneveld](/assets/images/teammates/avatar-kvz-4.jpg?dpl=dpl_B2d4XACVUtA1h8m6kRxZhWsda77Q)

#### Kevin van Zonneveld

Co-founder · Amsterdam, The Netherlands · Show bio

[](https://x.com/kvz)[](https://github.com/kvz)

Optimizing images is crucial for improving web performance. Large image files can slow down page load times, negatively affecting user experience and SEO rankings. In this post, we'll explore how to automate JPEG optimization using jpegoptim, a powerful tool that reduces image sizes without sacrificing quality. By integrating jpegoptim into your development workflow, you can ensure your web applications load quickly and efficiently.

<span aria-hidden="true" id="introduction-to-jpegoptim-and-its-benefits"></span>

## Introduction to jpegoptim and its benefits

When building web applications, image size significantly impacts page load times and user experience. jpegoptim is a free, open-source utility designed to optimize JPEG files by reducing their size while maintaining visual quality. Automating image optimization with jpegoptim streamlines your workflow and ensures that your application delivers optimized images without manual intervention.

<span aria-hidden="true" id="installing-and-setting-up-jpegoptim"></span>

## Installing and setting up jpegoptim

Before installing, note that the current stable release is 1.5.5 (released August 10, 2023); a beta version (1.5.6beta) is available if you need the latest features. jpegoptim requires the libjpeg development library as a dependency.

**For Linux distributions (e.g., Ubuntu):**

```bash
sudo apt-get update
sudo apt-get install libjpeg-dev
sudo apt-get install jpegoptim

```

**For macOS users:**

```bash
brew install jpegoptim

```

**Verify the installation:**

```bash
jpegoptim --version

```

<span aria-hidden="true" id="basic-usage-for-optimizing-jpeg-images"></span>

## Basic usage for optimizing JPEG images

To optimize a single JPEG image:

```bash
jpegoptim image.jpg

```

This command performs lossless optimization, reducing file size without any loss in image quality.

For lossy optimization with a specified maximum quality factor (e.g., 80):

```bash
jpegoptim --max=80 image.jpg

```

The `--max` option sets the maximum image quality factor, which can significantly reduce file size at the cost of some image quality. It strikes a good balance between size and quality.

<span aria-hidden="true" id="performance-impact"></span>

## Performance impact

Typical optimization results:

* Lossless optimization: 5–15% size reduction
* Lossy optimization (quality 80): 30–70% size reduction

Example:

```bash
# Original file: image.jpg (1.2MB)
jpegoptim --max=80 image.jpg
# Result: image.jpg (400KB)

```

<span aria-hidden="true" id="integrating-jpegoptim-into-build-scripts"></span>

## Integrating jpegoptim into build scripts

Automate image optimization by integrating jpegoptim into your build scripts. This ensures that images are optimized every time you build or deploy your project.

**Using a Makefile:**

```makefile
optimize-images:
	find assets/images -name '*.jpg' -exec jpegoptim {} +

```

**Explanation:**

* `find assets/images -name '*.jpg'` searches for all JPEG files in the `assets/images` directory.
* `-exec jpegoptim {} +` runs jpegoptim on all found files in batches for efficiency.

**Using npm scripts in `package.json`:**

```json
"scripts": {
  "optimize-images": "find assets/images -name '*.jpg' -exec jpegoptim {} +"
}

```

Run the script with:

```bash
npm run optimize-images

```

<span aria-hidden="true" id="automating-optimization-with-git-hooks-or-cicd-pipelines"></span>

## Automating optimization with git hooks or ci/cd pipelines

<span aria-hidden="true" id="using-a-git-pre-commit-hook"></span>

### Using a git pre-commit hook

Automate image optimization before each commit to ensure all images in your repository are optimized.

**Create a pre-commit hook script at `.git/hooks/pre-commit`:**

```bash
#!/bin/sh
# Exit on any error
set -e

# Check if assets/images directory exists
if [ -d "assets/images" ]; then
  find assets/images -name '*.jpg' -exec jpegoptim {} +
  # Only add if optimization succeeded
  git add assets/images
fi

```

**Make it executable:**

```bash
chmod +x .git/hooks/pre-commit

```

<span aria-hidden="true" id="integrating-with-cicd-pipelines"></span>

### Integrating with ci/cd pipelines

Automate image optimization in your continuous integration/continuous deployment (CI/CD) pipeline to ensure only optimized images are deployed.

For GitHub Actions, add the following to your workflow file (e.g., `.github/workflows/ci.yml`):

```yaml
name: Optimize Images

on:
  pull_request:
    paths:
      - '**.jpg'
      - '**.jpeg'

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

      - name: Cache optimized images
        uses: actions/cache@v3
        with:
          path: assets/images
          key: ${{ runner.os }}-images-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-images-

      - name: Install jpegoptim
        run: |
          sudo apt-get update
          sudo apt-get install -y libjpeg-dev jpegoptim

      - name: Optimize JPEG images
        run: |
          find assets/images -name '*.jpg' -o -name '*.jpeg' -exec jpegoptim {} +

      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v5
        with:
          commit-message: 'chore: optimize images'
          title: 'Optimize images'
          body: 'Automatically optimized images using jpegoptim'

```

<span aria-hidden="true" id="advanced-options-and-best-practices"></span>

## Advanced options and best practices

jpegoptim offers several advanced options to further fine-tune image optimization:

* **Strip metadata (EXIF data, comments):**\
  Remove unnecessary metadata to further reduce file size.

```bash
jpegoptim --strip-all image.jpg  
```

* **Progressive JPEG support:**\
  Convert images to or from progressive JPEG format.

```bash
# Convert to progressive JPEG  
jpegoptim --all-progressive image.jpg  
# Convert to non-progressive JPEG  
jpegoptim --all-normal image.jpg  
```

* **Target file size:**\
  Optimize an image to a target size (in KB).

```bash
jpegoptim --size=500 image.jpg  
```

* **Recursive optimization:**\
  Optimize images in a directory and its subdirectories.

```bash
jpegoptim --recursive assets/images/  
```

* **Preserve file timestamps:**\
  Maintain the original modification times of files.

```bash
jpegoptim --preserve image.jpg  
```

<span aria-hidden="true" id="best-practices"></span>

### Best practices

* **Backup original images:**\
  Always keep a backup of your original images before applying lossy compression.
* **Integrate early in development:**\
  Optimize images during the development process to prevent oversized files from being introduced.
* **Monitor web performance:**\
  Use tools like Google PageSpeed Insights or Lighthouse to measure the impact of image optimization.
* **Balance quality and size:**\
  Experiment with different quality settings to find the optimal balance for your project.

<span aria-hidden="true" id="conclusion"></span>

## Conclusion

Automating JPEG optimization with jpegoptim enhances web performance by reducing image sizes without compromising quality. By incorporating these techniques into your build scripts, git hooks, or CI/CD pipelines, you ensure that optimized images are consistently delivered to your users.

If you are interested in exploring further options for automated image optimization, consider checking out Transloadit's documentation [here](/docs/robots/image-optimize.md).

\#jpegoptim#jpeg-optimization#image-compression#automate-image-optimization#web-performance#ci-cd-integration#image-processing-service

### 👩‍💻 Join 20k+ developers

Sign up for our [monthly newsletter](/newsletters.md) to receive direct links to 3 exclusive tech — and 2 product updates. No less, no more.

Your email:

Get access

## File uploading and encoding. Made simple.

Transloadit streamlines file handling for developers, trusted by brands like Coursera and The New York Times. We’re known for a reliable API, top-notch support, and a strong commitment to open source, with projects like [Uppy⁠](https://uppy.io) and [Tus⁠](https://tus.io) setting standards in file processing.

[Sign up](/c/)[Book a Demo](https://survey.typeform.com/to/kRg47Xi5)

No credit card needed · 5 GB included in the free plan

Cancel anytime
