添加水印并在PHP中调整图像大小

时间:2017-10-01 11:20:38

标签: php image-resizing watermark

我需要在上传的图片上添加水印,并调整其大小以从该水印图像制作缩略图和图标。下面是我的功能代码添加水印但我无法找到如何将图像调整到给定的高度和宽度:

function watermark_image_new($target, $wtrmrk_file, $newcopy, $extension, $w = 0, $h = 0) {
$watermark = imagecreatefrompng($wtrmrk_file);
imagealphablending($watermark, false);
imagesavealpha($watermark, true);
//resize code
if ($w != 0) {
    list($width, $height) = getimagesize($target);
    if ($extension == 'jpeg' || $extension == 'jpg') {
        $img = imagecreatefromjpeg($target);
    } else if ($extension == 'png') {
        $img = imagecreatefrompng($target);
    }
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $img, 0, 0, 0, 0, $w, $h, $width, $height);
}
$img_w = imagesx($img);
$img_h = imagesy($img);
$wtrmrk_w = imagesx($watermark);
$wtrmrk_h = imagesy($watermark);
$dst_x = ($img_w / 2) - ($wtrmrk_w / 2); // For centering the watermark on any image
$dst_y = ($img_h / 2) - ($wtrmrk_h / 2); // For centering the watermark on any image
imagecopy($img, $watermark, $dst_x, $dst_y, 0, 0, $wtrmrk_w, $wtrmrk_h);
if ($extension == 'jpeg' || $extension == 'jpg') {
    imagejpeg($img, $newcopy, 100);
} else if ($extension == 'png') {
    imagepng($img, $newcopy);
}
imagedestroy($img);
imagedestroy($watermark);
}

1 个答案:

答案 0 :(得分:0)

使用Imagick解决案例的一个简单示例。要渲染水印并调整其大小并输出更改后的图像

<?php
$image = new Imagick();
$image->readImage("/path/to/image.jpg");
$watermark = new Imagick();
$watermark->readImage("/path/to/watermark.png");
// how big are the images?
$iWidth = $image->getImageWidth();
$iHeight = $image->getImageHeight();
$wWidth = $watermark->getImageWidth();
$wHeight = $watermark->getImageHeight();
if ($iHeight < $wHeight || $iWidth < $wWidth) {
 // resize the watermark
   $watermark->scaleImage($iWidth, $iHeight);
// get new size
$wWidth = $watermark->getImageWidth();
   $wHeight = $watermark->getImageHeight();
}
// calculate the position
$x = ($iWidth - $wWidth) / 2;
$y = ($iHeight - $wHeight) / 2;
$image->compositeImage($watermark, imagick::COMPOSITE_OVER, $x, $y);
header("Content-Type: image/" . $image->getImageFormat());
echo $image;