简体   繁体   中英

Adding logo as watermark, watermark poor quality

I am adding a transparant logo as watermark over an image using PHP. However, in the result the logo has poor quality (the image that is under it is high quality, so it's just the watermark). This is the code I use (its about the last 3 lines):

header("Content-Type: image/png");

$photo = imagecreatefromjpeg('photos/'.$photo['image']);
$height = imagesx($photo);
$width = imagesx($photo);
if ($width > $_POST['width']) {
    $r = $width / $_POST['width'];

    $newwidth = $width / $r;
    $newheight = $height / $r;
}
$image = imagecreatetruecolor($width, $height);

$image2 = imagecopyresampled($image, $photo, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

$position = explode(" ", $_POST['background']);

$image3 = imagecrop($image, [
    'x' => str_replace(array('-', 'px'), array('', ''), $position[0]),
    'y' => str_replace(array('-', 'px'), array('', ''), $position[1]),
    'width' => $_POST['width'],
    'height' => $_POST['height']
]);
$stamp = imagecreatefrompng('img/logo.png');
imagecopyresized($image3, $stamp, 0, 0, 0, 0, 147, 50, imagesx($stamp), imagesy($stamp));
imagepng($image3, "created/".time().".png", 9);

imagecopyresized will copy and scale and image. This uses a fairly primitive algorithm that tends to yield more pixelated results.

a simple example for a better quality is:

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?>

you should have a look at this post here

使用1-100的图像质量。

imagejpeg($image, $new_image_name, 99);

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