Home >Backend Development >PHP Tutorial >How to batch compress image file size using PHP
How to use PHP to batch compress image file sizes
Introduction:
With the development of the Internet, pictures are becoming more and more common in our daily lives. However, large and small picture files also bring storage and transmission problems. In order to reduce the size of image files and improve the loading speed of the website, we can use PHP to batch compress image file sizes. This article will introduce how to use PHP to batch compress image file sizes and provide relevant code examples.
Steps:
$directory = 'images/'; $fileList = glob($directory . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$targetWidth = 200; // 目标宽度 $targetQuality = 80; // 目标质量
foreach($fileList as $file) { $imageInfo = getimagesize($file); $sourceWidth = $imageInfo[0]; // 原始宽度 $sourceHeight = $imageInfo[1]; // 原始高度 $sourceImage = imagecreatefromjpeg($file); // 根据文件类型选择对应的函数 $targetHeight = round($sourceHeight * $targetWidth / $sourceWidth); // 计算目标高度 $targetImage = imagecreatetruecolor($targetWidth, $targetHeight); // 创建目标图像 imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight); // 图像复制和缩放 imagejpeg($targetImage, $file, $targetQuality); // 保存压缩后的图片 imagedestroy($sourceImage); // 释放资源 imagedestroy($targetImage); }
$directory = 'images/'; $fileList = glob($directory . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); $targetWidth = 200; // 目标宽度 $targetQuality = 80; // 目标质量 foreach($fileList as $file) { $imageInfo = getimagesize($file); $sourceWidth = $imageInfo[0]; // 原始宽度 $sourceHeight = $imageInfo[1]; // 原始高度 $sourceImage = imagecreatefromjpeg($file); // 根据文件类型选择对应的函数 $targetHeight = round($sourceHeight * $targetWidth / $sourceWidth); // 计算目标高度 $targetImage = imagecreatetruecolor($targetWidth, $targetHeight); // 创建目标图像 imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight); // 图像复制和缩放 imagejpeg($targetImage, $file, $targetQuality); // 保存压缩后的图片 imagedestroy($sourceImage); // 释放资源 imagedestroy($targetImage); }
Summary:
By using PHP to batch compress image file sizes, we can effectively reduce the size of image files and improve the loading speed of the website. This article provides a simple method and corresponding code example, but it needs to be adapted and extended according to the actual situation. I hope this article helps you better process and optimize image files.
The above is the detailed content of How to batch compress image file size using PHP. For more information, please follow other related articles on the PHP Chinese website!