Image compression in theme

[ad_1]

Hi, since some years I use tinyPNG for compressing my images (JPG, PNG, WebP) on upload to my WordPress image library.

From begin I wonder that is no function in WordPress. Now I made a small snippet for my theme. Did you think it is good enough?

function optimize_generated_image_sizes($metadata, $attachment_id) {
$upload_dir = wp_get_upload_dir()[‘basedir’]; // Basisverzeichnis des Uploads

foreach ($metadata[‘sizes’] as $size => $size_info) {
$file_path = $upload_dir . ‘/’ . $size_info[‘file’];
$safe_file_path = escapeshellarg($file_path); // Sicheres Escaping des Pfads

// JPEG-Optimierung
if ($size_info[‘mime-type’] === ‘image/jpeg’) {
$jpeg_command = “jpegoptim –strip-all –all-progressive –max=85 $safe_file_path”;
run_secure_command($jpeg_command);
}

// WebP-Konvertierung für JPEG und PNG
if ($size_info[‘mime-type’] === ‘image/jpeg’ || $size_info[‘mime-type’] === ‘image/png’) {
$webp_path = escapeshellarg($file_path . ‘.webp’);
$webp_command = “cwebp -q 80 $safe_file_path -o $webp_path”;
run_secure_command($webp_command);
}
}

return $metadata;
}
add_filter(‘wp_generate_attachment_metadata’, ‘optimize_generated_image_sizes’, 10, 2);

function run_secure_command($command) {
$descriptorspec = array(
0 => array(“pipe”, “r”), // stdin
1 => array(“pipe”, “w”), // stdout
2 => array(“pipe”, “w”) // stderr
);

$process = proc_open($command, $descriptorspec, $pipes);

if (is_resource($process)) {
fclose($pipes[0]); // Schließen der stdin
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);

$return_value = proc_close($process);

if ($return_value != 0) {
// Fehlerbehandlung, z. B. Loggen der Fehler oder Benachrichtigung des Administrators
error_log(“Fehler bei der Bildoptimierung: $stderr”);
}
}
}

[ad_2]
1 Comment
  1. It’s not really a good approach. WordPress has a default functionality to work with images, and it compresses JPEG images by default. you can configure it with filters:

    [apply_filters( ‘wp_editor_set_quality’, int $quality, string $mime_type );](https://developer.wordpress.org/reference/hooks/wp_editor_set_quality/)

    WP uses Imagick, GD, and AVIF modules to work with images. you can look in phpinfo() to see what image formats they support.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer