Lajos Arpad
Lajos Arpad

Reputation: 76444

Merge multiple pictures into one

Let's suppose I want to create a face generator, where I would design several pictures for face form, ears, noses, mouth, hair. Given a combination of those pictures how can I create a new picture in PHP? For instance, a simplified version:

There is face1.png, face2.png, nose1.png and nose2.png. How could I programmatically merge face1.png with nose2.png, so the result picture would hold content from both picture?

Upvotes: 2

Views: 2760

Answers (3)

Kicsi Viziló
Kicsi Viziló

Reputation: 675

There is a function named imagecopy. This function overrides a part of the destination image using a source image. The given part is specified as parameters. Before you tell me that this does not solve your problem, I have to add that the pixels in the destination picture will not be overriden by the pixels of the source picture if the pixels are transparent. You need to use imagealphablending and imagesavealpha on the source picture, like this:

public static function experimental($images, $width, $height, $dest = null) {

        $index = 0;

        if ($dest === null) {
            $dest = $images[$index++];
        }

        while ($index < count($images)) {
            imagealphablending($images[$index], true);
            imagesavealpha($images[$index], true );
            imagecopy($dest, $images[$index++], 0, 0, 0, 0, $width, $height);
        }

        return $dest;
    }

If we have these two pictures:

enter image description here enter image description here

The result will be this:

enter image description here

Upvotes: 1

Deep
Deep

Reputation: 2512

You really want make it with PHP? Ok.

1) You can use GD library for image processing. 2) You can use imagemagic PHP wrapper -- imagic.

But I think you should use canvas on client side. And for saving result you can send base64 png image representation of canvas (or separated layers/pictures) to backend.

Upvotes: 0

Tuure
Tuure

Reputation: 521

You've basically got three options: GD, Cairo or ImageMagic. I'd recommend using the Imagick class if it's available. If not, ImageMagick through PHP system calls. If that's not available, GD will probably suffice.

It depends on your server configuration, which of these are available and which would require additional packages to be installed.

There's a very simple example in the Imagick documentation of combining images: https://secure.php.net/manual/en/imagick.compositeimage.php

I also found this example for GD: Merge two PNG images with PHP GD library

Upvotes: 2

Related Questions