Home / Attachments / Smart convert images to webp
Duplicate Snippet

Embed Snippet on Your Site

Smart convert images to webp

Smart conversion of all photos to webp - determine the percentage of compression of photos
تبدیل تمامی عکس ها به فرمت webp - و تعیین مقدار درصد کمپرس

This PHP function, convert_to_webp, is designed for WordPress to automatically convert uploaded JPEG, PNG, and GIF images into the WebP format, which is a more efficient image format that provides superior compression and quality. The function checks if the GD library is available, loads the appropriate image type, and converts it to WebP with an initial quality setting of 70%. If the resulting WebP file is larger than the original, it iteratively reduces the quality until it is smaller or reaches a minimum threshold. If successful, the original image is deleted to save space. This ensures that your website serves lighter images, enhancing loading times and overall performance.
این کد توسط محمدسعید کتاب الهی نوشته شده است

Code Preview
php
<?php
function convert_to_webp($file) {
    $file_path = $file['file'];
    $file_type = $file['type'];
    // Only for JPEG, PNG, and GIF images
    if (in_array($file_type, ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'])) {
        $webp_path = preg_replace('/\.(jpe?g|png|gif)$/i', '.webp', $file_path);
        
        // Check if the GD library is available
        if (!function_exists('gd_info')) {
            error_log("GD library is not available.");
            return $file; // Return original file if GD is not available
        }
        // Convert image to WebP with default quality of 70%
        $default_quality = 70;
        $image = null;
        // Load the image based on its type
        switch ($file_type) {
            case 'image/jpeg':
            case 'image/jpg':
                $image = imagecreatefromjpeg($file_path);
                break;
            case 'image/png':
                $image = imagecreatefrompng($file_path);
                break;
            case 'image/gif':
                $image = imagecreatefromgif($file_path);
                break;
            default:
                error_log("Unsupported image type: $file_type");
                return $file; // Return original file if unsupported
        }
        // Check if the image was successfully loaded
        if ($image) {
            // Convert to WebP
            imagewebp($image, $webp_path, $default_quality);
            // Check the file size of the WebP file
            if (filesize($webp_path) > filesize($file_path)) {
                // Reduce quality until the size is smaller than the original file
                for ($quality = $default_quality - 10; $quality > 10; $quality -= 10) { // Avoid going below 10
                    imagewebp($image, $webp_path, $quality);
                    if (filesize($webp_path) < filesize($file_path)) {
                        break;
                    }
                }
            }
            // If the WebP file size is still larger, delete the WebP file
            if (filesize($webp_path) > filesize($file_path)) {
                unlink($webp_path);
            } else {
                // Delete the original file if it exists
                if (file_exists($file_path)) {
                    unlink($file_path);
                }
                $file['file'] = $webp_path;
                $file['type'] = 'image/webp';
            }
            // Free up resources
            imagedestroy($image);
        } else {
            // Log error if the image failed to load
            error_log("Failed to create image from: $file_path");
        }
    }
    return $file;
}
add_filter('wp_handle_upload', 'convert_to_webp');

Comments

Add a Comment