<?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}'>";
网友回复
有没有开源的项目将图片视频声音文字转场特效编排自动生成剪映草稿json文件?
有没有摄像头捕获眼球转动操作鼠标的开源代码?
localstorage如何生成自增的键值对进行增删改查?
python有没有将python脚本与python运行环境一键打包成exe的代码?
nodejs如何执行浏览器中运行的js代码?
iframe中如何阻止其他域名网页的打开或跳转?
webrtc如何实现多人音频电话会议?
如何实现uni.connectSocket兼容web与小程序app端的websocket通讯?
webrtc如何浏览器中实现多人群音视频通话会议?
indexdb中的表结构与数据如何导出导入恢复?