使用 PHP 在服务器上压缩 jpeg
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10870129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compress jpeg on server with PHP
提问by Meir
I have a site with about 1500 JPEG images, and I want to compress them all. Going through the directories is not a problem, but I cannot seem to find a function that compresses a JPEG that is already on the server (I don't want to upload a new one), and replaces the old one.
我有一个包含大约 1500 张 JPEG 图像的站点,我想将它们全部压缩。浏览目录不是问题,但我似乎找不到压缩服务器上已经存在的 JPEG 的功能(我不想上传新的),并替换旧的。
Does PHP have a built in function for this? If not, how do I read the JPEG from the folder into the script?
PHP 有内置函数吗?如果没有,如何将文件夹中的 JPEG 读入脚本?
Thanks.
谢谢。
回答by Emil Vikstr?m
I prefer using the IMagickextension for working with images. GD uses too much memory, especially for larger files. Here's a code snippet by Charles Hallin the PHP manual:
我更喜欢使用Imagick扩展来处理图像。GD 使用太多内存,尤其是对于较大的文件。这是Charles Hall在 PHP 手册中的一段代码:
$img = new Imagick();
$img->readImage($src);
$img->setImageCompression(Imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(90);
$img->stripImage();
$img->writeImage($dest);
$img->clean();
回答by Emil Vikstr?m
you're not telling if you're using GD, so i assume this.
你没有告诉你是否在使用 GD,所以我假设这一点。
$img = imagecreatefromjpeg("myimage.jpg"); // load the image-to-be-saved
// 50 is quality; change from 0 (worst quality,smaller file) - 100 (best quality)
imagejpeg($img,"myimage_new.jpg",50);
unlink("myimage.jpg"); // remove the old image
回答by Neograph734
You will need to use the php gd library for that... Most servers have it installed by default. There are a lot of examples out there if you search for 'resize image php gd'.
您将需要为此使用 php gd 库...大多数服务器默认安装了它。如果您搜索“resize image php gd”,则有很多示例。
For instance have a look at this page http://911-need-code-help.blogspot.nl/2008/10/resize-images-using-phpgd-library.html
例如看看这个页面http://911-need-code-help.blogspot.nl/2008/10/resize-images-using-phpgd-library.html
回答by Daniel
The solution provided by vlzvl works well. However, using this solution, you can also overwrite an image by changing the order of the code.
vlzvl 提供的解决方案效果很好。但是,使用此解决方案,您还可以通过更改代码顺序来覆盖图像。
$image = imagecreatefromjpeg("image.jpg");
unlink("image.jpg");
imagejpeg($image,"image.jpg",50);
This allows you to compress a pre-existing image and store it in the same location with the same filename.
这允许您压缩预先存在的图像并将其存储在具有相同文件名的相同位置。

