1

这是覆盖在图像上的文本和渐变在文本周围有一些奇怪的像素化的问题,但我不知道为什么。

输出图像-->放大

这是代码:

<?php
function hex2rgb($hex) {
    $rgb[0] = hexdec(substr($hex, 0, 2));
    $rgb[1] = hexdec(substr($hex, 2, 2));
    $rgb[2] = hexdec(substr($hex, 4, 2));
    return $rgb;
}

$sourceImage = imagecreatefromstring(file_get_contents("source.jpg"));

$imagePadding = 10;

$height = imagesy($sourceImage);
$width = imagesx($sourceImage);

$baseImage = imagecreatetruecolor($width, $height);

$backgroundColor = imagecolorallocate($baseImage, 0, 0, 0);
imagefill($baseImage, 0, 0, $backgroundColor);

imagecopyresampled($baseImage, $sourceImage, 0, 0, 0, 0, $width, $height, $width, $height);

//==== GRADIENT ====//
// Modified from: http://stackoverflow.com/questions/14684622/blend-transparent-gradient-with-an-image-using-php-gd-library
$gradientCanvas = imagecreatetruecolor($width, $height);
$transColor = imagecolorallocatealpha($gradientCanvas, 0, 0, 0, 127);

imagefill($gradientCanvas, 0, 0, $transColor);

$color = hex2rgb("000000");
$start = -40;
$stop = 120;
$range = $stop - $start;

for ($y = 0; $y < $height; ++$y) {
    $alpha = $y <= $start ? 0 : round(min(($y - $start) / $range, 1) * 127);
    $newColor = imagecolorallocatealpha($gradientCanvas, $color[0], $color[1], $color[2], $alpha);
    imageline($gradientCanvas, 0, $y, $width, $y, $newColor);
}

imagecopyresampled($baseImage, $gradientCanvas, 0, 0, 0, 0, $width, $height, $width, $height);

//==== TEXT ====//
putenv('GDFONTPATH=.');
$font = "HelveticaNeueBold.ttf";


$white = imagecolorallocate($baseImage, 255, 255, 255);
imagettftext($baseImage, 14, 0, $imagePadding, $imagePadding + 16, $white, $font, "Foobar");

header('Content-Type: image/jpeg');
imagejpeg($baseImage);
imagedestroy($baseImage);
imagedestroy($sourceImage);
?>
4

2 回答 2

2

imagejpeg http://php.net/manual/en/function.imagejpeg.php的默认质量为 ~75,您需要将其设置为 100

imagejpeg($baseImage, null, 100);
于 2013-10-18T15:48:19.007 回答
2

主要原因 - 您使用 JPG 作为输出和输入图像。编辑 JPG 图像通常会导致图像失真。尝试使用 PNG 图像作为来源。或者尝试将 imagejpeg() 的“质量”参数设置为 100

于 2013-10-18T15:46:21.323 回答