简体   繁体   中英

Calculate image size in percentage in php

I have a piece of code which adds a watermark to the bottom right corner of an uploaded photo. However, the watermark doesen't change size according to the uploaded photo as I want it to do. I'd like to scale it calculated on percentage, so the watermark is always 10% of the uploaded photo and placed in the bottom right corner. How can this be done?

This is my code:

// 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);

If you have PHP 5.5+, do it like this:

// 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);

Note: This will work well with source images roughly rectangular in size. For extreme aspect ratios, you might need to use more sophisticated scaling.

For pre-PHP5.5, but at least PHP 4, you can scale an image like this:

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%

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