Search code examples
phpphp-gd

Rotate image on top of background-image


I have two images. one is a jpg image of a rotated polaroid frame polaroid.jpg. The other is just an ordinary image image.jpg.

I'm trying to rotate the image, and then put it on top of the polaroid-image, and then show the merged images as one jpg-image.

I think I'm pretty close with the following code, but I can't manage to get the transparancy working. The uncovered zone of the rotated image is black instead of transparent. What am I doing wrong? I've added a comment to the lines that are relevant for getting a transparent background for the top-image.

$bg_src = "polaroid.jpg";

$img_src = "image.jpg";

$outputImage = imagecreatefromjpeg($bg_src);

$img = imagecreatefromjpeg($img_src);

// This should create transparent background.
$bgd_color = imagecolorallocatealpha($img, 0, 0, 0, 127); 

// This should assign the transparent background to the uncovered zone after rotation
$img = imagerotate($img, 10, $bgd_color);

// This should make sure the alpha transparency gets saved
imagesavealpha($img, true);

$img_x = imagesx($img);

$img_y = imagesy($img);

imagecopymerge($outputImage,$img,156,50,0,0,$img_x,$img_y,100);

header('Content-type: image/jpeg');

imagejpeg($outputImage);

imagedestroy($outputImage);

Solution

  • Figured it out after some heave searching. Turns out to be real simple. I just changed this line:

    imagesavealpha($img, true);
    

    to this:

    imagecolortransparent($img,$bgd_color);
    

    yay! :)