How can PHP be used to compress images, specifically JPEG and GIF files, in a directory by a certain percentage?

To compress images in a directory by a certain percentage using PHP, you can use the GD library functions to resize the images. You can calculate the new dimensions based on the desired compression percentage and then save the compressed images in the same directory.

<?php
$directory = 'path/to/images/directory/';
$compressionPercentage = 50; // 50% compression

$files = glob($directory . '*.jpg');
foreach ($files as $file) {
    list($width, $height) = getimagesize($file);
    $newWidth = $width * ($compressionPercentage / 100);
    $newHeight = $height * ($compressionPercentage / 100);

    $image = imagecreatefromjpeg($file);
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

    imagejpeg($newImage, $file, 75); // 75% quality
    imagedestroy($image);
    imagedestroy($newImage);
}
?>