PHP quality preview photos
With the help of what can be achieved with the same quality pictures as a preview vkontakte.ru (not adv)?
I use the library GD.
Image quality vkontakte:
Quality pictures to my script:
Big photo: Link
In all of this photo vkontakte with the best quality weighs 7Kb, and my 16K ...
My script:
<?php
function _makeThumbnail($image, $dest, $ext)
{
$imageType = exif_imagetype($image);
switch ($imageType)
{
case IMAGETYPE_JPEG:
$img = imagecreatefromjpeg($image);
break;
case IMAGETYPE_PNG:
$img = imagecreatefrompng($image);
break;
case IMAGETYPE_GIF:
$img = imagecreatefromgif($image);
break;
default:
throw new Exception('Bad extension');
}
$width = imagesx($img);
$height = imagesy($img);
list($widthX, $heightX) = array('130', '130');
if ($width > $widthX || $height > $heightX)
{
if ($height > $width)
{
$ratio = $heightX / $height;
$newHeight = $heightX;
$newWidth = $width * $ratio;
}
else
{
$ratio = $widthX / $width;
$newWidth = $widthX;
$newHeight = $height * $ratio;
}
$previewImg = imagecreatetruecolor($newWidth, $newHeight);
$palsize = ImageColorsTotal($img);
for ($i = 0; $i < $palsize; $i++)
{
$colors = ImageColorsForIndex($img, $i);
ImageColorAllocate($previewImg, $colors['red'], $colors['green'], $colors['blue']);
}
imagecopyresized($previewImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$name = $dest;
switch ($imageType)
{
case IM开发者_如何学运维AGETYPE_JPEG:
imagejpeg($previewImg, $name . '.' . $ext, 100);
break;
case IMAGETYPE_PNG:
imagesavealpha($previewImg, true);
imagepng($previewImg, $name . '.' . $ext, 9);
case IMAGETYPE_GIF:
imagegif($previewImg, $name . '.' . $ext);
break;
default:
throw new Exception();
}
}
imagedestroy($previewImg);
imagedestroy($img);
}
Actually necessary to solve two problems. Make the best quality and thus reduce the size of the preview.
Using imagecopyresampled()
instead of imagecopyresized()
usually solves the acute problem.
That said, GD's JPG compression is not great by any standard. It is nowhere near Photoshop's excellent export filter in terms of image quality vs. file size. ImageMagick tends to be at least slightly better - if good compression is very important, it maybe is worth a look.
@Pekka is correct, and as for the second issue you can use imagejpeg($img, $filename, $quality)
to optimize the thumbnail.
here is a guide and some samples to help you out with that.
精彩评论