Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP image re-sizing

Tags:

php

I have a PHP script that re-sizes my JPEG images. But, for some reason The images are being distorted, even though I programmed it to calculate the x or y (depending on the photo orientation) proportionally. The quality is 100, so I don't get why it would be making them distorted. What am I doing wrong?

EDIT

The original image is 3264px x 2448px

The original Image: http://imgur.com/DOsKf&hMAOh#0

Re-sized: http://imgur.com/DOsKf&hMAOh#1

Thanks

The Code:

<?php

$im = ImageCreateFromJpeg('IMG_0168.jpg');

//Find the original height and width.

$ox = imagesx($im);
$oy = imagesy($im);

//Now we will determine the new height and width. For this example maximum height will    
be 500px and the width will be 960px. To prevent inproper proportions we need to know 
if the image is portrate or landscape then set one dimension and caluate the other. 

$height = 500;
$width = 960;
if($ox < $oy)   #portrate
{
   $ny = $height;
   $nx = floor($ox * ($ny / $oy)); 
} 
else #landscape
{
   $nx = $width;
   $ny = floor($oy * ($nx / $ox)); 
} 

//Then next two functions will create a new image resource then copy the original image     
to the new one and resize it.

$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0, 0, 0, 0, $nx, $ny, $ox, $oy);

//Now we just need to save the new file.

imagejpeg($nm, 'smallerimagefile2.jpg', 100);

?>
like image 333
Matt Avatar asked Oct 06 '22 09:10

Matt


1 Answers

Use

imagecopyresampled($nm, $im, 0, 0, 0, 0, $nx, $ny, $ox, $oy);

Instead of

imagecopyresized($nm, $im, 0, 0, 0, 0, $nx, $ny, $ox, $oy);

Explanation:

imagecopyresized() allows you to change the size of an image quickly and easily, but has the downside of producing fairly low-quality pictures. imagecopyresampled() which takes the same parameters as imagecopyresized() and works in the same way with the exception that the resized image is smoothed. The downside is that the smoothing takes more CPU effort, so the image takes longer to produce.

Details of the functions:

  • imagecopyresampled: http://php.net/manual/en/function.imagecopyresampled.php

  • imagecopyresized: http://php.net/manual/en/function.imagecopyresized.php

like image 65
gurudeb Avatar answered Oct 10 '22 04:10

gurudeb