โ† Back to Blog

How to Convert Images to WebP Format

2026-04-05 ยท 5 min read

โ† Back to Blog

How to Convert Images to WebP Format

ยท 5 min read

Choosing the Right WebP Conversion Mode

When converting images to WebP, first decide between lossy and lossless mode. If the source is a JPG (already lossy), use lossy WebP; if the source is a PNG (lossless, especially with transparent background), usually use lossless WebP to preserve transparency and graphical precision; for graphics with transparent backgrounds (logos, icons), also use lossless WebP.

Lossy WebP quality parameter ranges from 0โ€“100, similar to JPG. The recommended starting point is quality 75โ€“80, which usually achieves the best balance between visual quality and file size โ€” about 30% smaller than equivalent quality JPG. For product images requiring high quality output, use 85โ€“90.

Converting Using Online Tools

Steps to convert to WebP using our online image conversion tool: (1) open the image conversion tool and upload a JPG or PNG image; (2) select WebP in the output format options; (3) choose lossy or lossless mode and set quality parameters (for lossy mode); (4) click convert and download the .webp file. The tool processes locally in the browser without server uploads, supports drag-and-drop, and typically supports PNG, JPG, GIF, BMP input formats.

Using the cwebp Command-Line Tool

# ๅฎ‰่ฃ… libwebp ๅทฅๅ…ท้›† / Install libwebp tools
# macOS: brew install webp
# Ubuntu/Debian: sudo apt install webp

# ๆœ‰ๆŸ่ฝฌๆข๏ผˆๆŽจ่่ดจ้‡ 75-85๏ผ‰
# Lossy conversion (recommended quality 75-85)
cwebp -q 80 photo.jpg -o photo.webp

# ๆ— ๆŸ่ฝฌๆข๏ผˆ้€‚ๅˆ PNG๏ผ‰
# Lossless conversion (suitable for PNG)
cwebp -lossless icon.png -o icon.webp

# ไฟ็•™ EXIF ๅ…ƒๆ•ฐๆฎ
# Preserve EXIF metadata
cwebp -q 80 -metadata exif photo.jpg -o photo.webp

# ๆ‰น้‡่ฝฌๆขๆ‰€ๆœ‰ JPG
# Batch convert all JPGs
for f in *.jpg; do
  cwebp -q 80 "$f" -o "${f%.jpg}.webp"
done

# ๆŸฅ็œ‹่ฝฌๆข็ป“ๆžœไฟกๆฏ
# View conversion result info
webpinfo photo.webp

Converting to WebP in Python

from PIL import Image
import os
from pathlib import Path

def convert_to_webp(input_path, output_path=None, quality=80, lossless=False):
    """
    ๅฐ†ๅ›พ็‰‡่ฝฌๆขไธบ WebP ๆ ผๅผ
    Convert image to WebP format
    """
    input_path = Path(input_path)
    if output_path is None:
        output_path = input_path.with_suffix('.webp')

    with Image.open(input_path) as img:
        original_size = input_path.stat().st_size

        # ๅฏนไบŽ RGBA ๅ›พ็‰‡๏ผŒไฟ็•™้€ๆ˜Žๅบฆ / For RGBA images, preserve transparency
        if img.mode == 'RGBA' or lossless:
            img.save(str(output_path), 'WEBP', lossless=True, quality=100)
        else:
            if img.mode != 'RGB':
                img = img.convert('RGB')
            img.save(str(output_path), 'WEBP', quality=quality)

        new_size = Path(output_path).stat().st_size
        reduction = (1 - new_size / original_size) * 100
        print(f"{input_path.name}: {original_size//1024}KB โ†’ {new_size//1024}KB ({reduction:.1f}% smaller)")

# ๆ‰น้‡่ฝฌๆข็›ฎๅฝ• / Batch convert directory
def batch_convert(directory, quality=80):
    for ext in ['*.jpg', '*.jpeg', '*.png']:
        for f in Path(directory).glob(ext):
            convert_to_webp(f, quality=quality)

batch_convert('./images', quality=80)

Converting with Sharp in Node.js

// ๅฎ‰่ฃ… / Install: npm install sharp
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');

// ๅ•ๆ–‡ไปถ่ฝฌๆข / Single file conversion
async function toWebP(inputPath, quality = 80) {
  const outputPath = inputPath.replace(/\.(jpg|jpeg|png|gif)$/i, '.webp');
  const info = await sharp(inputPath)
    .webp({ quality, lossless: false })
    .toFile(outputPath);
  console.log(`Converted: ${info.size} bytes โ†’ ${outputPath}`);
  return outputPath;
}

// ๆ‰น้‡่ฝฌๆข / Batch conversion
async function batchToWebP(dir, quality = 80) {
  const files = fs.readdirSync(dir).filter(f => /\.(jpg|jpeg|png)$/i.test(f));
  let totalSaved = 0;
  for (const file of files) {
    const inputPath = path.join(dir, file);
    const outputPath = await toWebP(inputPath, quality);
    const origSize = fs.statSync(inputPath).size;
    const newSize = fs.statSync(outputPath).size;
    totalSaved += origSize - newSize;
  }
  console.log(`Total saved: ${(totalSaved / 1024 / 1024).toFixed(2)} MB`);
}

batchToWebP('./public/images', 80);

Automatically Serving WebP in Nginx

On production servers, configure Nginx to automatically detect whether the browser supports WebP, then serve the WebP version or fall back to the original format. This requires keeping both WebP and original versions, with the server intelligently selecting based on the Accept header.

# Nginx ้…็ฝฎ WebP ่‡ชๅŠจๆœๅŠก / Nginx config for automatic WebP serving
map $http_accept $webp_suffix {
  default "";
  "~*webp" ".webp";
}

server {
  location ~* \.(jpg|jpeg|png)$ {
    add_header Vary Accept;
    try_files $uri$webp_suffix $uri =404;
  }
}

Conversion Quality Verification

After conversion, verify that WebP image quality meets requirements. The most direct method is to compare the original and WebP version side by side in the browser at 100% zoom, inspecting detail areas. You can also use objective metrics like SSIM (Structural Similarity Index) to quantify quality differences: an SSIM value above 0.95 generally means visually indistinguishable quality.

For important product images or marketing images, have team members conduct visual quality review, especially checking product details, text clarity, and color accuracy. Once the minimum acceptable quality parameter (like 75) is confirmed, you can confidently apply the same settings for batch conversion of all similar images.

Using WebP in Next.js and Modern Frameworks

Modern frontend frameworks provide excellent WebP support. Next.js's component automatically converts and serves WebP (or AVIF) versions without manual conversion. Simply use Next.js's Image component instead of regular img tags, and the framework automatically handles format conversion, lazy loading, responsive sizing, and all other optimizations.

Try the online tool now โ€” no installation, completely free.

Open Tool โ†’

Try the free tool now

Use Free Tool โ†’