P
P
Pavel2021-03-18 16:47:14
PHP
Pavel, 2021-03-18 16:47:14

How to reduce Imagick file size?

I do image processing, divide into pieces. After all the manipulations, the image file size is many times larger than the original one.

$pieces = 2; // или 3
$picture = new Imagick('./test.jpg');
$picture_width = $picture->getImageWidth();
$picture_height = $picture->getImageHeight();
$gap = 20;
$piece_width = intval($picture_width / $pieces);

$canvas = new Imagick();
$canvas->newImage($picture_width + $gap * ($pieces - 1), $picture_height, 'none');
$picture->cropImage($piece_width, $picture_height, 0, 0);
$canvas->compositeImage($picture, Imagick::COMPOSITE_ADD, 0, 0 );

for ($i = 1; $i < $pieces; $i++) {
    $piece = new Imagick('./test.jpg');
    $piece->cropImage($piece_width, $picture_height, $piece_width * $i, 0);
    $canvas->compositeImage($piece, Imagick::COMPOSITE_ADD, $gap * $i + $piece_width * $i, 0 );
}

$canvas->setImageFormat('png');

header("Content-Type: image/png");
echo $canvas;
die;


Original image - 393KB
605359197bba2455540669.jpeg

Results over 1.5MB!
6053599139c4c853143021.png

605359b20a5d1657441491.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
N, 2021-03-18
@Fernus

https://www.php.net/manual/en/imagick.setimagecomp...
https://www.php.net/manual/en/imagick.setcompressi...
UPD :
Try 75...heavy shouldn't affect image quality...
UPD2 :
PNG didn't see at first...

For a PNG image, `setImageCompressionQuality()` is not work at all, the length of the generated files are totally same.
But I found an effective way, that is use `setOption('png:compression-level', 9)`, the value range is 0-9.

Source

N
neol, 2021-03-18
@neol

So the original is in jpeg, and the result is in png.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question