简体   繁体   中英

Resize and watermark for image in PHP

I am wanting to resize and add watermark to the uploaded image. I am able to resize the image successfully but once I apply the watermark, the watermark has a black background rather than transparent.

$watermark_l = "source/watermark_l.png";
$size_wm_l = getimagesize($watermark_l);
$watermark_l = imagecreatefrompng($watermark_l);
$filename = "input/$gallery/$file";
header('Content-Type: image/jpeg');
list($width, $height) = getimagesize($filename);
$x_large = 2000;
$y_large = 1333;
$image_p = imagecreatetruecolor($x_large, $y_large);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $x_large, $y_large, $width, $height);
imagecopy($image_p, $watermark_l, 0, 0, 0, 0, $size_wm_l[0], $size_wm_l[1]);
imagejpeg($image_p, "output/$gallery/2000x1333_$file", 100);

Try to enable alpha blending on images after ImageCreate's:

ImageAlphaBlending($watermark_l,true);
ImageAlphaBlending($image_p,true);

Here's a good example for adding watermark on images using PHP -

<?php
// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefrompng('stamp.png');
$im = imagecreatefromjpeg('photo.jpeg');

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// Copy the stamp image onto our photo using the margin offsets and the photo 
// width to calculate positioning of the stamp. 
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

Source - http://php.net/manual/en/image.examples-watermark.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM