如何使用PHP调整图像上的水印大小?

时间:2015-12-09 17:32:24

标签: php gd

您好我试图在上传的图片上调整水印png,但是我无法弄明白,我做错了什么。

这是我的代码:

// BEGIN WATERMARK

$watermark = imagecreatefrompng ('watermark.png');
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
$image = imagecreatetruecolor($watermark_width, $watermark_height);
$_Dim[x] = imageSX($destImage);
$_Dim[y] = imageSY($destImage);
$logo_Dim[x] = imageSX($watermark);
$logo_Dim[y] = imageSY($watermark);
$x = $_Dim[x] - $logo_Dim[x];
$y = $_Dim[y] - $logo_Dim[y];
imagecopy ($destImage, $watermark, $x, $y, 0, 0, $watermark_width, $watermark_height);
imagedestroy ($watermark);

// END WATERMARK

2 个答案:

答案 0 :(得分:2)

使用:imagecopyresizedimagecopyresampled

$watermark = imagecreatefrompng ('watermark.png');
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);

// this is an example to resized your watermark to 0.5% from their original size.
// You can change this with your specific new sizes.
$percent = 0.5;
$newwidth = $watermark_width * $percent;
$newheight = $watermark_height * $percent;

// create a new image with the new dimension.
$new_watermark = imagecreatetruecolor($newwidth, $newheight);

// Retain image transparency for your watermark, if any.
imagealphablending($new_watermark, false);
imagesavealpha($new_watermark, true);

// copy $watermark, and resized, into $new_watermark
// change to `imagecopyresampled` for better quality
imagecopyresized($new_watermark, $watermark, 0, 0, 0, 0, $newwidth, $newheight, $watermark_width, $watermark_height);

$_Dim[x] = imageSX($destImage);
$_Dim[y] = imageSY($destImage);
$logo_Dim[x] = imageSX($new_watermark);
$logo_Dim[y] = imageSY($new_watermark);
$x = $_Dim[x] - $logo_Dim[x];
$y = $_Dim[y] - $logo_Dim[y];
imagecopy ($destImage, $new_watermark, $x, $y, 0, 0, $newwidth, $newheight);
imagedestroy ($new_watermark);

注意:我假设你有另一个imageSX& imageSY函数,因为内置函数都是小写的:imagesx& imagesy

编辑1 :php中的函数名称不区分大小写,但最好调用函数,因为它们出现在声明中。

编辑2 :添加更多代码以保持透明度。

答案 1 :(得分:1)

您可以使用此功能调整图章大小。不要使用imagecopyresized,因为它会损坏您的图像,您的质量会降低。更好的是imagecopyresampledimagesavealphaimagealphablending为您提供透明背景标记

$image = imagecreatefromstring(file_get_contents('The_img.jpg'));
$stamp = imagecreatefrompng('the_watermark.png');

$stamp_new = imagecreatetruecolor(100,50);
imagealphablending($stamp_new, false);
imagesavealpha($stamp_new, true);
imagecopyresampled($stamp_new, $stamp, 0, 0, 0, 0, 100, 50, imagesx($stamp),imagesy($stamp));

$margin = ['right' => 20, 'bottom' => 20]; // Смещение от края
imagecopy($image, $stamp_new,
imagesx($image) - imagesx($stamp_new) - $margin['right'],
imagesy($image) - imagesy($stamp_new) - $margin['bottom'],
0, 0, imagesx($stamp_new), imagesy($stamp_new));
$imageName = 'newimage.jpg';
$dirName = 'test_folder';
if(!file_exists($dirName)){
    mkdir($dirName, 0755, true);
    imagepng($image, $dirName.'/'.$imageName);
} else {
    imagepng($image, $dirName.'/'.$imageName);
}

ImageDestroy($image);
ImageDestroy($stamp);