2013-10-18 34 views
1

这是问题的文字覆盖在图像和渐变周围有一些奇怪的图像周围的文字,但我不知道为什么。PHP GD自由文本渲染与pixilation

Output image - >Zoomed

下面的代码:

<?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); 
?> 
+0

它们看起来非常相似,标准JPEG工件,你有没有尝试摆弄质量参数?例如'imagejpeg($ baseImage,NULL,90);' – fvu

+0

你无法避免它。这是使用JPEG压缩的自然结果。 –

+0

强烈建议你切换到使用PNG。 JPEG图像中的文字始终会造成某种质量问题。 –

回答

2

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