phpgdlib

Generating thumbnails using PHP causes bad image quality


$sourcePath = 'images/'; // Path of original image
$sourceUrl = '';
$sourceName = 'photo1.jpg'; // Name of original image
$thumbPath = 'thumbs/'; // Writeable thumb path
$thumbUrl = 'thumbs/';
$thumbName = "test_thumb.jpg"; // Tip: Name dynamically
$thumbWidth = 100; // Intended dimension of thumb

// Beyond this point is simply code.
$sourceImage = imagecreatefromjpeg("$sourcePath/$sourceName");
$sourceWidth = imagesx($sourceImage);
$sourceHeight = imagesy($sourceImage);

$targetImage = imagecreate($thumbWidth,$thumbWidth);
imagecopyresized($targetImage,$sourceImage,0,0,0,0,$thumbWidth,$thumbWidth,imagesx($sourceImage),imagesy($sourceImage));
imagejpeg($targetImage, "$thumbPath/$thumbName");

// By now, the thumbnail is copied into the $thumbpath
// as the file name specified in $thumbName, so display
echo "<img src='$thumbUrl$thumbName' alt=''>";

The above code gives me a thumbnail and that's great, but the image quality is awful. It looks like the image has had the colours inverted and it looks like it has been squashed. I've had headaches all day doing this. Any one have any ideas?


Solution

  • Use imagecreatetruecolor instead of imagecreate and imagecopyresampled instead of imagecopyresized.