Compress jpeg on server with PHP

I have a website with approximately 1,500 JPEG images, and I want to compress them all. Going through directories is not a problem, but I can not find a function that compresses JPEG, which is already on the server (I do not want to load a new one), and replaces the old one.

Does PHP have a built-in function for this? If not, how did I read the jpeg from the folder in the script?

Thanks.

+7
source share
4 answers

you donโ€™t say if you are 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 
+14
source

I prefer to use the IMagick extension for working with images. GD uses too much memory, especially for large files. Here is the Charles Hall code snippet 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(); 
+19
source

You will need the php gd library for this ... Most servers are installed by default. There are many examples if you are looking for "resize php gd image".

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

0
source

The solution provided by vlzvl works well. However, using this solution, you can also overwrite the 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 save it in the same place with the same file name.

0
source

All Articles