php - 如何在 php 中使用 imagejpeg 在 Kb 中设置特定压缩
问题描述
我正在尝试将上传的图像压缩到 200Kb 的特定大小。我不想压缩它们超出需要的程度,并且使用像 PNG 这样的无损压缩是不够的。只需将其设置imagejpeg($image, null, 40)
为为不同的图像创建不同的压缩大小。有没有办法以字节为单位设置所需的压缩大小,或者至少有一些算法可以找出压缩输出而无需imagejpeg()
从 100 循环到 0 质量?
解决方案
我找到了一种在上传之前使用 ob 来查看图像文件大小的方法,所以我在循环中使用它
// Get get new image data
ob_start();
// Build image with minimal campression
imagejpeg($newImage, NULL, 100);
// Get the size of the image file in bytes
$size = ob_get_length();
// Save new image into a variable
$compressedImage = addslashes(ob_get_contents());
// Clear memory
ob_end_clean();
// If image is larger than 200Kb
if ($size > 200000) {
// This variable will decrease by 2 every loop to try most combinations
// from least compressed to most compressed
$compressionValue = 100;
for ($i=0; $i < 50; $i++) {
$compressionValue = $compressionValue - 2;
ob_start();
imagejpeg($newImage, NULL, $compressionValue);
$size = ob_get_length();
// Overwrite old compressed image with the new compressed image
$compressedImage = addslashes(ob_get_contents());
// Clear memory
ob_end_clean();
// If image is less than or equal to 200.5Kb stop the loop
if ($size <= 200500) {
break;
}
}
}
这本身也得到了非常好的优化。即使尝试 50 种组合,对于 1.5Mb 的起始图像,整个过程也只需要几毫秒。
推荐阅读
- c++ - std::remove() 可以按预期使用文字但不能使用取消引用的迭代器
- reactjs - Material-UI 自动完成 event.target
- java - 如何用嵌套的 for 循环解决这个问题
- java - 仅在特定片段处添加工具栏菜单
- python - 将数据框单元格乘以矩阵值的问题
- sql - 如何在 PostgreSQL 中编写选择查询以遍历选择查询返回的数组
- python - 获取 NameError:Vapoursynth/Python 中未定义名称“视频”
- oracle - 如何使用 curl 在 Oracle Apex 中提交页面
- jira - 在 JIRA 中返回没有父级的问题的查询
- rxjs - RxJS:使用自定义逻辑匹配两个可观察对象