<?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}'>";
网友回复
如何让ai帮我自动在小红书或抖音上自动根据需求截流与潜在客户聊天拉客?
如果用go编写一个在virtualbox中启动的简单操作系统?
go如何搭建一个零信任网络?
如何用python实现一个公网代理访问软件?
如何用go实现一个公网代理访问软件?
如何用python实现一个内网穿透打洞程序,实现内网的80端口暴露到公网上可以访问?
如何用go实现一个内网穿透打洞程序,实现内网的80端口暴露到公网上可以访问?
何为Shadowsocks 代理?
python如何实现类似php的opendir目录相互隔离的fastcgi多租户虚拟空间?
nodejs如何实现类似php的opendir目录相互隔离的fastcgi多租户虚拟空间?


