ConFoo: Call for paper is now Open

Imagick::flattenImages

(PECL imagick 2.0.0)

Imagick::flattenImagesMerges a sequence of images

Descrierea

Imagick Imagick::flattenImages ( void )

Merges a sequence of images. This is useful for combining Photoshop layers into a single image.

Valorile întoarse

Întoarce TRUE în caz de succes.

Erori/Excepții

Emite ImagickException în caz de eroare.

add a note add a note

User Contributed Notes 3 notes

up
1
ureimers
7 months ago
Small correction to Jairu5's code:

If you want to set the background color of a transparent image you have to set it _before_ loading the image.
Flattening images by default uses the background color 'white'. That's why Jairu5's code seem to work at first, but only until you want to actually change the background color to something different than white.

Try using this instead:

<?php

$im
= new Imagick();
$im->setImageBackgroundColor('green');
$im->readimage('image.png');

$im = $im->flattenImages();

$im->setImageFormat('jpg');
$im->writeImage('image.jpg');

?>
up
0
Samuel Fine (hi at samuelfine dot com)
2 years ago
This is also useful for accurately converting .ico files to .png. (Other types as well, in theory, but I've only tested ico->png.) Simply using setFormat will create a valid .png file, but will result in image artifacts if the original .ico had any transparency. The following code will create an accurate copy:

<?php

$im
= new Imagick();

// When dealing with .ico files, make sure to setFormat before loading the image or you'll get a nasty exception. See https://bugs.php.net/bug.php?id=58515 for more details.
$im->setFormat("ico");

$im->readImage("favicon.ico");

$im = $im->flattenImages(); // Thanks for the tip, Jairu5!

$im->setFormat("png");

$new = fopen("favicon.png", "w");
$im->writeImageFile($new);
$im->clear();
$im->destroy();

?>
up
0
Jairu5
3 years ago
Note that the function returns an Imagick object and does not modify the existing object. Below is my code for converting a PNG with transparency into a JPG with a background color. This code illustrates the difference.

<?php

$im
= new Imagick('image.png');
$im->setImageBackgroundColor('white');

$im->flattenImages(); // This does not do anything.
$im = $im->flattenImages(); // Use this instead.

$im->setImageFormat('jpg');
$im->writeImage('image.jpg');

?>
To Top