+
95
-

回答

<?php
/**
*图片压缩到指定的体积大小
* $original_file 原始图片路径
* $resized_file 压缩后图片路径
* $max_file_size 压缩大小 单位kb
* $image_quality 图片质量 1-100
*/
function compresstosize($original_file, $resized_file, $max_file_size,$image_quality=100) {


$original_image = imagecreatefromjpeg($original_file);



do {
$temp_stream = fopen('php://temp', 'w+');
$saved = imagejpeg($original_image, $temp_stream, $image_quality--);
rewind($temp_stream);
$fstat = fstat($temp_stream);
fclose($temp_stream);

$file_size = $fstat['size'];
}
while (($file_size > $max_file_size) && ($image_quality >= 0));

if (-1 == $image_quality) {
die("无法压缩这么小");
// echo "Unable to get the file that small. Best I could do was $file_size bytes at image quality 0.\n";
} else {
// echo "Successfully resized $original_file to $file_size bytes using image quality $image_quality. Resized file saved as $resized_file.\n";
imagejpeg($original_image, $resized_file, $image_quality + 1);
}
}
$rand = rand(1, 10000000);
compresstosize("bg.jpg","resized.jpg","10000");
echo "<h2>压缩到指定大小kb的图</h2>"; echo "<img src='resized.jpg?rand={$rand}'>";

网友回复

我知道答案,我要回答