How to Convert Images to Different Formats (JPEG, PNG, WebP) in PHP

How to Convert Images to Different Formats (JPEG, PNG, WebP) in PHP

Introduction

Images are a key part of any web application, but using the right format is crucial for performance and compatibility. JPEG, PNG, and WebP serve different purposes:

  • JPEG – Best for photographs with lossy compression.
  • PNG – Best for transparent images with lossless quality.
  • WebP – Best for optimized images with better compression than JPEG/PNG.

In this guide, we’ll learn how to convert images between different formats using GD Library and Imagick, ensuring your images are optimized for speed and quality.

Convert PNG to JPEG and vice versa
Convert PNG/JPEG to WebP for better compression
Optimize images while converting formats
Use both GD Library and Imagick for format conversion

1. Setting Up PHP for Image Conversion

Check if GD Library or Imagick is Installed

For GD Library:

Run:

php -m | grep gd

If missing, enable it in php.ini:

extension=gd

For Imagick:

Run:

php -m | grep imagick

If missing, install it using:

sudo apt install php-imagick

GD Library is built-in, while Imagick provides more advanced image manipulation features.

2. Convert PNG to JPEG in PHP

Using GD Library

function convertPngToJpeg($source, $destination, $quality = 90) {
    $image = imagecreatefrompng($source);
    $white = imagecreatetruecolor(imagesx($image), imagesy($image));
    imagefill($white, 0, 0, imagecolorallocate($white, 255, 255, 255));
    imagecopy($white, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));

    imagejpeg($white, $destination, $quality);
    imagedestroy($image);
    imagedestroy($white);

    echo "PNG converted to JPEG successfully!";
}

// Example usage
convertPngToJpeg("input.png", "output.jpg", 80);

Why Fill with White?

PNG supports transparency, but JPEG doesn’t.
We replace transparency with a white background before saving as JPEG.

3. Convert JPEG to PNG in PHP

Using GD Library

function convertJpegToPng($source, $destination) {
    $image = imagecreatefromjpeg($source);
    imagepng($image, $destination);
    imagedestroy($image);

    echo "JPEG converted to PNG successfully!";
}

// Example usage
convertJpegToPng("input.jpg", "output.png");

PNG supports lossless compression and transparency, making it ideal for high-quality images.

4. Convert JPEG/PNG to WebP in PHP

Using GD Library

function convertToWebP($source, $destination, $quality = 80) {
    $info = getimagesize($source);
    $mime = $info['mime'];

    switch ($mime) {
        case 'image/jpeg':
            $image = imagecreatefromjpeg($source);
            break;
        case 'image/png':
            $image = imagecreatefrompng($source);
            break;
        default:
            die("Unsupported image format!");
    }

    imagewebp($image, $destination, $quality);
    imagedestroy($image);

    echo "Image converted to WebP successfully!";
}

// Example usage
convertToWebP("input.jpg", "output.webp", 80);

WebP reduces file sizes by ~30% compared to JPEG and PNG.

5. Converting Images Using Imagick (Advanced Method)

Imagick provides more control over image formats and supports more file types than GD.

Convert PNG to JPEG with Imagick

function convertPngToJpegImagick($source, $destination, $quality = 85) {
    $image = new Imagick($source);
    $image->setImageFormat("jpeg");
    $image->setImageCompressionQuality($quality);
    $image->writeImage($destination);
    
    echo "PNG converted to JPEG using Imagick!";
}

// Example usage
convertPngToJpegImagick("input.png", "output.jpg", 80);

Imagick provides better image processing quality with less code.

Convert JPEG/PNG to WebP with Imagick

function convertToWebPImagick($source, $destination, $quality = 80) {
    $image = new Imagick($source);
    $image->setImageFormat("webp");
    $image->setImageCompressionQuality($quality);
    $image->writeImage($destination);
    
    echo "Image converted to WebP using Imagick!";
}

// Example usage
convertToWebPImagick("input.jpg", "output.webp", 80);

Imagick automatically handles transparency and optimizations better than GD.

6. Optimizing Images While Converting Formats

While converting, we can optimize images for performance using compression.

Best Compression Settings for Web Optimization

JPEG (imagejpeg()) – Use 75-85 quality for balance
PNG (imagepng()) – Use compression level 6-8
WebP (imagewebp()) – Use quality 70-80 for sharp images

7. Handling Batch Image Conversions

If you need to convert multiple images at once, use a loop:

$files = glob("images/*.png"); // Get all PNG files

foreach ($files as $file) {
    $newFile = str_replace(".png", ".jpg", $file);
    convertPngToJpeg($file, $newFile, 85);
}

This script will convert all .png files in the images/ folder to .jpg.

Best Practices for Image Conversion in PHP

Use GD Library for simple conversions, Imagick for advanced processing.
Optimize image quality settings to reduce file size.
Use WebP format for better performance in modern browsers.
Always check image format before processing.
Batch process images to save time and resources.

Conclusion

Converting images in PHP is essential for performance and compatibility. By using GD Library or Imagick, you can convert PNG, JPEG, and WebP efficiently while optimizing for web performance.

JPEG is best for high-quality photos.
PNG is best for transparency and sharp graphics.
WebP is best for modern web performance.

By following best practices and implementing format conversions, you can deliver fast-loading, high-quality images in your PHP applications 🚀.

Leave a Reply