2

I am trying to install a watermark in the middle of my image, but every time it shows a weird square which is not fully transparent. This is the result of my code:

enter image description here

This is my code:

<?php
header("Content-type: image/png");

$image = imagecreatefromjpeg('http://www.sideshowtoy.com/wp-content/uploads/2016/03/dc-comics-batman-v-superman-woner-woman-sixth-scale-hot-toys-feature-902687.jpg');
$watermark = imagecreatefrompng('https://d5odq6jbm6umf.cloudfront.net/assets/img/video-play-button-transparent.png');
imagesavealpha($watermark,true);

$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
$dest_x = (imagesx($image) - $watermark_width)/2;
$dest_y = (imagesy($image) - $watermark_height)/2;
imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 100);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
?>
timclutton
  • 12,682
  • 3
  • 33
  • 43
  • 1
    Possible duplicate of [Using GD in PHP, how can I make a transparent PNG watermark on PNG and GIF files ? (JPG files work fine)](http://stackoverflow.com/questions/4437557/using-gd-in-php-how-can-i-make-a-transparent-png-watermark-on-png-and-gif-files) – buster Jul 25 '16 at 17:04
  • or duplicate of http://stackoverflow.com/questions/5529306/i-cant-use-transparent-background-with-imagecopymerge - There are many with answers to this question. – Jim Jul 25 '16 at 17:06

1 Answers1

2

I usually create a new true colour resource and copy everything into it. This ensures GD doesn't get too quirky. It's a little bit more resource intensive, but should be negligible for most cases.

Below is your code modified to create a new image, copy in the jpeg, and then overlay the partially transparent watermark:

<?php
$image = imagecreatefromjpeg('http://www.sideshowtoy.com/wp-content/uploads/2016/03/dc-comics-batman-v-superman-woner-woman-sixth-scale-hot-toys-feature-902687.jpg');
$img_w = imagesx($image);
$img_h = imagesy($image);
$new = imagecreatetruecolor($img_w, $img_h);
imagecopy($new, $image, 0, 0, 0, 0, $img_w, $img_h);
imagedestroy($image);

$watermark = imagecreatefrompng('https://d5odq6jbm6umf.cloudfront.net/assets/img/video-play-button-transparent.png');
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
$dest_x = ($img_w - $watermark_width) / 2;
$dest_y = ($img_h - $watermark_height) / 2;
imagecopy($new, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);

header('Content-type: image/png');
imagejpeg($new);
imagedestroy($new);
imagedestroy($watermark);

Result:

Wonder Woman! Na na na na na!

timclutton
  • 12,682
  • 3
  • 33
  • 43