4

I'm fairly new to iMagick and have only found very limited documentation on the PHP library. I'm happily resizing images and writing them back to the hard drive, but I'm failing completely to compress the images using JPG for instance.

This is the code I'm using so far:

function scale_image($size = 200,$extension)
{
    if(!file_exists(ALBUM_PATH . $this->path . $this->filename . $extension))
    {
        $im = new imagick(ALBUM_PATH . $this->path . $this->filename);
        
        $width = $im->getImageWidth();
        $height = $im->getImageHeight();
        if($width > $height)
            $im->resizeImage($size, 0, imagick::FILTER_LANCZOS, 1); 
        else 
            $im->resizeImage(0 , $size, imagick::FILTER_LANCZOS, 1); 
        
        $im->setImageCompression(true);
        $im->setCompression(Imagick::COMPRESSION_JPEG);
        $im->setCompressionQuality(20); 
        
        $im->writeImage(ALBUM_PATH . $this->path . $this->filename . $extension); 
        $im->clear(); 
        $im->destroy(); 
    }
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Rob Forrest
  • 7,329
  • 7
  • 52
  • 69

3 Answers3

11

Try this:

$im->setImageCompression(Imagick::COMPRESSION_JPEG);
$im->setImageCompressionQuality(20);
kovshenin
  • 31,813
  • 4
  • 35
  • 46
  • This is what I use and works fine for me. The quality is set to 87 by default. I found setting it to 80 was better for my type of use. – TheCarver Sep 10 '13 at 20:38
3

setImageCompression seems to expect an integer as parameter rather than a boolean (see : http://www.php.net/manual/en/function.imagick-setimagecompression.php).

I think image compression may work if you disable this line :

$im->setImageCompression(true);
2

The full list of compression formats from a source code:

const COMPRESSION_NO = 1;
const COMPRESSION_BZIP = 2;
const COMPRESSION_FAX = 6;
const COMPRESSION_GROUP4 = 7;
const COMPRESSION_JPEG = 8;
const COMPRESSION_JPEG2000 = 9;
const COMPRESSION_LOSSLESSJPEG = 10;
const COMPRESSION_LZW = 11;
const COMPRESSION_RLE = 12;
const COMPRESSION_ZIP = 13;
const COMPRESSION_DXT1 = 3;
const COMPRESSION_DXT3 = 4;
const COMPRESSION_DXT5 = 5;
const COMPRESSION_ZIPS = 14;
const COMPRESSION_PIZ = 15;
const COMPRESSION_PXR24 = 16;
const COMPRESSION_B44 = 17;
const COMPRESSION_B44A = 18;
const COMPRESSION_LZMA = 19;
const COMPRESSION_JBIG1 = 20;
const COMPRESSION_JBIG2 = 21;

Original documentation: http://www.imagemagick.org/script/command-line-options.php#compress

German Khokhlov
  • 1,724
  • 16
  • 15