Resize images without warping
I am trying to create a thumbnail with the gd library, but my thumbnail is always garbled. I want to crop the image starting from the center respecting the new resolution and losing the old aspect ratio.
What I have tried:
$im = ImageCreateFromJPEG($target_file);
$n_width = 500; // Fix the width of the thumb nail images
$n_height = 500; // Fix the height of the thumb nail imaage
$width = ImageSx($im); // Original picture width is stored
$height = ImageSy($im); // Original picture height is stored
$newimage = imagecreatetruecolor($n_width, $n_height);
imagecopyresampled($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
$thumb_target = $target_dir . $filename_without_ext . '-thumb.' . $params['file_ext'];
ImageJpeg($newimage, $thumb_target);
chmod("$thumb_target", 0777);
Tried changing imagecreatetruecolor
to imagecrop
, but still not with the behavior I want.
Please let me know if I was not clear enough.
source to share
Solved using ImageManipulator . Found a solution in this answer .
My final code:
$im = new ImageManipulator($target_file);
$centreX = round($im->getWidth() / 2);
$centreY = round($im->getHeight() / 2);
$x1 = $centreX - 500;
$y1 = $centreY - 500;
$x2 = $centreX + 500;
$y2 = $centreY + 500;
$im->crop($x1, $y1, $x2, $y2);
$im->save($target_dir . $filename_without_ext . '-thumb.' . $params['file_ext']);
source to share
Your new dimensions produce a square; this will always distort the thumbnail if the original image was not (almost) square. If you calculate the new dimensions from the old one (find a larger size, divide by 500 pixels, multiply the smaller one by the same ratio), you get a non-square sketch with the same proportion, therefore, it will not be distorted.
If you wanted your thumbs to be square, you could convert the smaller dimension to 500px, create the image as I suggested above, and then crop to 500x500.
source to share