PHP - 压缩图像以符合文件大小限制 [英] PHP - Compress Image to Meet File Size Limit

查看:713
本文介绍了PHP - 压缩图像以符合文件大小限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须上传符合最大宽度尺寸和最大文件尺寸的图片文件。

I have to upload image files that meet a max width dimension and max file size.

我有检查宽度大小的代码,并调整图像大小以满足最大图像宽度。

I have the code that checks width size and resizes the image to meet the max image width.

但是,当我保存文件时,我可以设置质量

However, when I am saving the file I can set the quality

imagejpeg( $imgObject , 'resized/50.jpg' , 50 ); //save image and set quality

我想要做的是避免设置标准质量所提交的图像与质量高度不同,并且可能开始较低。

What I would like to do is avoid setting a standard quality, as the images being submitted vary highly from quality and may be low to begin with.

图片的质量应设置为尽可能高,而不超过最大文件大小限制。

The quality of the image should be set as high as possible without going over the max file size limit.

我唯一的解决方案是以不同的质量保存图像的多个版本,检查每个文件大小并选择最好的一个。这工作,但是非常缓慢和过程密集。

The only solution I have is to save several versions of the image at varying qualities, check each file size and pick the best one. This works but is very slow and process intensive.

有关如何改善的任何建议吗?

Any suggestions on how this could be done better?

感谢

推荐答案

不幸的是,估计最终文件大小不是你可以做的,因为你没有访问JPEG编码器的内部状态。

Unfortunately, estimating final file size isn't something you can do as you have no access to the JPEG encoder's internal state.

你可以做的一件事是压缩一个较小版本的图像,并从那里推断。将宽度和高度减少四个意味着计算机只处理像素的十六分之一。这里的技巧是如何准备代表性的测试图像。使用imagecopyresampled()或imagecopyresized()缩放图像将无法工作。它会改变压缩特性。相反,你想做的是从原始图像复制每隔四个8x8图块:

One thing you can do is compress a smaller version of the image and extrapolate from there. Reducing the width and height by four means the computer has to deal with only one sixteenth of the pixels. The trick here is how to prepare a representative test image. Scaling the image down using imagecopyresampled() or imagecopyresized() won't work. It changes the compression characteristic too much. Instead, what you want to do is copy every fourth 8x8 tile from the original image:

$width1 = imagesx($img1);
$height1 = imagesy($img1);
$width2 = floor($width1 / 32) * 8;
$height2 = floor($height1 / 32) * 8;
$img2 = imagecreatetruecolor($width2, $height2);
for($x1 = 0, $x2 = 0; $x2 + 8 < $width2; $x1 += 32, $x2 += 8) {
    for($y1 = 0, $y2 = 0; $y2 + 8 < $height2; $y1 += 32, $y2 += 8) {
        imagecopy($img2, $img1, $x2, $y2, $x1, $y1, 8, 8);
    }
}

在各种质量级别压缩较小的图像,相关文件大小。将它们乘以16应该得到一个合理的估计,你会得到与原始图像。

Compress the smaller image at various quality levels and get the respected file sizes. Multiplying them by 16 to should yield a reasonably good estimate of what you would get with the original image.

这篇关于PHP - 压缩图像以符合文件大小限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆