Compress jpeg on server with PHP

ⅰ亾dé卋堺 提交于 2019-12-17 20:09:34

问题


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.

Does PHP have a built in function for this? If not, how do I read the JPEG from the folder into the script?

Thanks.


回答1:


you're not telling if you're using GD, so i assume this.

$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



回答2:


I prefer using the IMagick extension for working with images. GD uses too much memory, especially for larger files. Here's a code snippet by Charles Hall in the PHP manual:

$img = new Imagick();
$img->readImage($src);
$img->setImageCompression(Imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(90);
$img->stripImage();
$img->writeImage($dest); 
$img->clean();



回答3:


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'.

For instance have a look at this page http://911-need-code-help.blogspot.nl/2008/10/resize-images-using-phpgd-library.html




回答4:


The solution provided by vlzvl works well. However, using this solution, you can also overwrite an image by changing the order of the code.

    $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.



来源:https://stackoverflow.com/questions/10870129/compress-jpeg-on-server-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!