Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress PNG files in PHP

I am generating PNG file with cairo extension of PHP. The image contains a background and a text. Now I want to compress these images by PHP after its generated by cairo. Is there any library to do this?

I found pngcrush tool. But its a command line tool. I dont want to invoke system call. If there is not PHP solution a C solution would do. In that case I'll make a PHP extension.

I have read this related question. But there is no answer in it.

like image 816
Shiplu Mokaddim Avatar asked Oct 26 '25 06:10

Shiplu Mokaddim


2 Answers

You can use imagepng() ...

//If you don't already have a handle to the image and it's just on the file system...
$im = imagecreatefrompng("yourGenerateFile.png");
$quality = 5; //0 - 9 (0= no compression, 9 = high compression)
imagepng($im, 'file/to/save.png', $quality);  //leave out filename if you want it to output to the buffer
imagedestroy($im);
like image 197
Brad Harris Avatar answered Oct 27 '25 20:10

Brad Harris


I would take a look at PngOptimizer. You can get the source for it at the bottom of the page, and it has a separated CLI version too.

Only problem is that source is C++ , not ANSI C. I have never made a PHP extension, so i don't know if it makes a difference.

like image 24
tereško Avatar answered Oct 27 '25 19:10

tereško