Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image resizing without deformation

Tags:

php

gd

I'm trying to create a thumbnail with gd library, but my thumbnail is always distorted. What I want is to cut the image starting from the center respecting a new resolution and losing the old proportion.

What I've 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 to change imagecreatetruecolor to imagecrop but still not with the behavior that I want.

Please let me know if I was not clear enough.

like image 999
William Weckl Avatar asked Mar 04 '26 08:03

William Weckl


1 Answers

Solved it using ImageManipulator library. Found the 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']);
like image 144
William Weckl Avatar answered Mar 06 '26 20:03

William Weckl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!