2013-10-18 86 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