PHPのお勉強!

PHP TOP

Imagick::setCompressionQuality

(PECL imagick 2, PECL imagick 3)

Imagick::setCompressionQualityオブジェクトのデフォルトの圧縮品質を設定する

説明

public Imagick::setCompressionQuality(int $quality): bool

オブジェクトのデフォルトの圧縮品質を設定します。

警告

このメソッドは、たとえば Imagick::newPseudoImage などで作った新しい画像に対してだけ使えるものです。 既存の画像に対しては Imagick::setImageCompressionQuality() を使う必要があります。

パラメータ

quality

1 から 100 の間の int 1 = 高圧縮品質。 100 = 低圧縮品質。を表します。

戻り値

成功した場合に true を返します。

例1 Imagick::setCompressionQuality()

<?php
function setCompressionQuality($imagePath, $quality) {

$backgroundImagick = new \Imagick(realpath($imagePath));
$imagick = new \Imagick();
$imagick->setCompressionQuality($quality);
$imagick->newPseudoImage(
$backgroundImagick->getImageWidth(),
$backgroundImagick->getImageHeight(),
'canvas:white'
);

$imagick->compositeImage(
$backgroundImagick,
\Imagick::COMPOSITE_ATOP,
0,
0
);

$imagick->setFormat("jpg");
header("Content-Type: image/jpg");
echo
$imagick->getImageBlob();
}

?>

add a note

User Contributed Notes 3 notes

up
30
deeps chennai
14 years ago
A note for people who just couldn't get this working..

With PHP 5.1.6, the below works:

<?php
$img
->setCompression(Imagick::COMPRESSION_JPEG);
$img->setCompressionQuality(80);
?>

However, with higher versions of PHP (I tried on PHP 5.2.10), the code has no effect (and there are no exceptions or warnings thrown by Imagick as well).

The code that works instead is:

<?php
$img
->setImageCompression(Imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(80);
?>

and this is backwards compatible (Works on PHP 5.1.6 as well as 5.2.10)
up
5
charles dot hall at sas dot com
14 years ago
I had to insert a call to "stripImage()" in order to actually see the filesize shrink.

<?php
$img
= new Imagick();
$img->readImage($src);
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(90);
$img->stripImage();
$img->writeImage($dest);
?>
up
-4
nVaux.com
16 years ago
Sebastian's example works excellent, just one minor spelling mistake, it will give you an error otherwise.

<?php
$img
->setCompression(Imagick::COMPRESSION_JPEG);
$img->setCompressionQuality(80);
?>

I used Sebastians example, and made one that compresses all the images within a directory:

<?php
$images
= new Imagick(glob('images/*.jpg'));

foreach(
$images as $image)
{
// compression methods, see "Contants"-page for Imagick
$image->setCompression(imagick::COMPRESSION_JPEG);
// a value between 1 and 100, 1 = high compression, 100 low compression
$image->setCompressionQuality(80);
$image->writeImage();
}

?>