Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP crop image to fix width and height without losing dimension ratio

im looking to create thumbnails that has 100px by 100px dimension. i've seen many articles explaining the methods but most end up having the width!=height if the dimension ratio is to be kept.

for example, i have a 450px by 350px image. i would like to crop to 100px by 100px. if i were to keep the ratio, i would end up having 100px by 77px. this makes it ugly when im listing these images in a row and column. however, a image without dimension ratio will look terrible as well.

i've seen images from flickr and they look fantastic. for example:
thumbnail: http://farm1.static.flickr.com/23/32608803_29470dfeeb_s.jpg
medium size: http://farm1.static.flickr.com/23/32608803_29470dfeeb.jpg
large size: http://farm1.static.flickr.com/23/32608803_29470dfeeb_b.jpg

tks

like image 510
chrizonline Avatar asked Jul 15 '10 13:07

chrizonline


People also ask

How do you fix a picture ratio?

Click Upload an image and select the image you want to crop. Under step 2, click the Fixed Aspect Ratio button, then enter that ratio, such as 5 and 2, and click Change. Drag a rectangle over the image to select the area you want. Move the selection as needed, then click Crop.

How do I crop a custom ratio?

To set a custom crop ratio, tap on the preset dimensions at the top of your screen. Adjust the width and height of your custom crop ratio and adjust to get to your ideal dimensions. Select OK to apply your changes.


1 Answers

This is done by only using a part of the image as the thumbnail which has a 1:1 aspect ratio (mostly the center of the image). If you look closely you can see it in the flickr thumbnail.

Because you have "crop" in your question, I'm not sure if you didn't already know this, but what do you want to know then?

To use cropping, here is an example:

//Your Image
$imgSrc = "image.jpg";

//getting the image dimensions
list($width, $height) = getimagesize($imgSrc);

//saving the image into memory (for manipulation with GD Library)
$myImage = imagecreatefromjpeg($imgSrc);

// calculating the part of the image to use for thumbnail
if ($width > $height) {
  $y = 0;
  $x = ($width - $height) / 2;
  $smallestSide = $height;
} else {
  $x = 0;
  $y = ($height - $width) / 2;
  $smallestSide = $width;
}

// copying the part into thumbnail
$thumbSize = 100;
$thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

//final output
header('Content-type: image/jpeg');
imagejpeg($thumb);
like image 84
Sven Koschnicke Avatar answered Sep 28 '22 06:09

Sven Koschnicke