Why Image Optimization Matters
Images typically account for 50-80% of a web page's total size. Optimizing them is the single biggest performance win for most websites.
WebP Format
# Install cwebp
sudo apt install -y webp
# Convert JPEG to WebP
cwebp -q 80 image.jpg -o image.webp
# Batch convert
for file in *.jpg; do
cwebp -q 80 "$file" -o "${file%.jpg}.webp"
doneWebP is 25-35% smaller than JPEG at equivalent quality.
Resize to Proper Dimensions
# Install ImageMagick
sudo apt install -y imagemagick
# Resize maintaining aspect ratio
convert image.jpg -resize 1200x image-1200.jpg
# Batch resize
for file in *.jpg; do
convert "$file" -resize 1200x -quality 85 "optimized/$file"
doneNginx WebP Serving
# Serve WebP to browsers that support it
map $http_accept $webp_suffix {
default "";
"~*webp" ".webp";
}
location ~* \.(jpg|jpeg|png)$ {
add_header Vary Accept;
try_files $uri$webp_suffix $uri =404;
}Lazy Loading
<img src="image.jpg" loading="lazy" alt="Description">Native browser lazy loading defers loading images until they are near the viewport, reducing initial page weight.