1

Here's the problem the text overlayed over the image and gradient has some weird pixilation around the text, but I can't work out why.

Output image --> Zoomed

Here's the code:

<?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);
?>
fvu
  • 32,488
  • 6
  • 61
  • 79
Gcoop
  • 3,372
  • 4
  • 26
  • 35
  • They look quite similar to standard JPEG artifacts, have you tried fiddling with the quality parameter? Eg `imagejpeg($baseImage,NULL,90);` – fvu Oct 18 '13 at 15:47
  • You can't avoid it. It's a natural outcome of using JPEG compression. – Marc B Oct 18 '13 at 15:56
  • Highly recommend you just switch to using PNG. Text in JPEG images will always create some sort of quality issues. – BA_Webimax Oct 18 '13 at 15:51

2 Answers2

2

The main reason - you are using JPG as output and input image. Editing JPG images often causes the image distortions. Try to use a PNG image as a source. Or try set the "quality" parameter of imagejpeg() to 100

2

The default quality of imagejpeg http://php.net/manual/en/function.imagejpeg.php is ~75, you will want to set this to 100

imagejpeg($baseImage, null, 100);
cmorrissey
  • 8,493
  • 2
  • 23
  • 27