在php中以百分比计算图像大小

时间:2013-05-19 22:05:57

标签: php image

我有一段代码在上传的照片的右下角添加了水印。但是,水印不会根据我想要的上传照片改变大小。我想按百分比计算它,因此水印始终是上传照片的10%并放在右下角。如何才能做到这一点?

这是我的代码:

// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefromgif('../images/watermark.gif');

$marge_right = 5;
$marge_bottom = 5;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

$im = imagecreatefromjpeg($file_tmp)
imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right,
 imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), 30);

2 个答案:

答案 0 :(得分:0)

如果您使用PHP 5.5+,请执行以下操作:

// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefromgif('../images/watermark.gif');
$im = imagecreatefromjpeg($file_tmp);

$marge_right = 5;
$marge_bottom = 5;

$percent = 10;
$factor = 1 - ($percent/100); 

$stampscaled = imagescale ($stamp, $factor * $imagesx($im));

$sx = imagesx($stampscaled);
$sy = imagesy($stampscaled);

imagecopymerge($im, $stamp, imagesx($im) - $marge_right - $sx,
 imagesy($im) - $marge_bottom - $sy, 0, 0, $factor * imagesx($im), $factor * imagesy($im), 30);

注意:这适用于大致呈矩形的源图像。对于极端宽高比,您可能需要使用更复杂的缩放。

答案 1 :(得分:0)

对于PHP5.5之前的版本,但至少是PHP4,您可以像这样缩放图像:

function scale($image, $percentage)
{
    $w = imagesx($image) * $percentage;
    $h = imagesy($image) * $percentage;
    $newimage = imagecreatetruecolor($w, $h);
    imagecopyresized($newimage, $image, 0, 0, 0, 0, $w, $h,
                                                   imagesx($image), imagesy($image));
    return $newimage;
}

$scaledImage = scale($originalImage, 0.5); // scale by 50%