PDA

View Full Version : resizing images, no quality loss



kjavia795
June 14th, 2008, 12:21
is there any way to have an image, when it is uploaded to the site, to be changed to a specific size in pixels, without any stretching or loss of quality?

JohnN
June 14th, 2008, 13:19
yes and no. provided you are downscaling the picture, you can. You cannot upscale a picture (eg: make it bigger) without loosing quality.

If you have a 300x200 image and want 100x100, the only way you can do it without distorting is to make first to crop it to a ratio of 100x100 (1:1) then rescale it.

heres a couple of functions that should help:


function resize($file, $size, $location){

$location_file = explode(".",$file);
$location = $location_file['0'].$location;

list($width, $height) = getimagesize($file);

if ($width > $height) {
$src_w = $src_h = $height;
$src_y = 0;
$src_x = round(($width - $height) / 2);
} else {
$src_w = $src_h = $width;
$src_x = 0;
$src_y = round(($height - $width) / 2);
}

$dst_image = imagecreatetruecolor($size, $size);

if (preg_match('/png/',$file))
$src_image = imagecreatefrompng($file);
else if (preg_match('/gif/',$file))
$src_image = imagecreatefromgif($file);
else $src_image = imagecreatefromjpeg($file);

imagecopyresampled ( $dst_image, $src_image, 0, 0, $src_x, $src_y, $size, $size, $src_w, $src_h );

imagegif($dst_image,$location);

}

function crop($file){


$img = imagecreatetruecolor(256,80);
//alter according to final image size

$org_img = imagecreatefromgif($file);

$ims = getimagesize($image);
imagecopy($img,$org_img, 0, 0, 0, 128, 256, 256);
//twiddle to get correct

imagegif($img,$file);

imagedestroy($img);

}


enjoy.

Sammie
June 16th, 2008, 21:28
Sorry, deleted