Wednesday, November 27, 2013

Quick JPEG Optimization to Speed Up Your Web Site

If you would like to quickly optimize the jpeg images for your web site, here's a quick method that works pretty good.

First, download jpegtran.exe, and save it to C:\

Download your image files to C:\Users\administrator\Desktop\files, or change the path in the code below to point to the root folder where you want to search for images to optimize. The script will crawl through subdirectories, so don't worry about the directory structure under the path that you specify.

Open a PowerShell prompt (you may need to "run as administrator" depending on your security settings). If your files are in a different path, or you placed jpegtran.exe edit the code below to reflect those difference. Run the code below.


$files = Get-ChildItem -Path C:\Users\administrator\Desktop\files -Recurse | where {$_.Extension -eq ".jpg"}
foreach($file in $files){
    [string]$image = $file.FullName
    [string]$cmd = "C:\jpegtran.exe -copy none -optimize $image $image"
    Invoke-Expression $cmd
}

The way the previous code is written, it will overwrite the existing file with the optimized one, so make a copy of them first if you want to keep the original as well.

I hope that helps. I optimized all of the JPEGs on one of my sites in a few minutes, and that includes writing the PowerShell code above.