Calculating image size ratio for resizing Calculating image size ratio for resizing php php

Calculating image size ratio for resizing


Here's code from my personal grab bag of image resizing code. First, data you need:

list($originalWidth, $originalHeight) = getimagesize($imageFile);$ratio = $originalWidth / $originalHeight;

Then, this algorithm fits the image into the target size as best it can, keeping the original aspect ratio, not stretching the image larger than the original:

$targetWidth = $targetHeight = min($size, max($originalWidth, $originalHeight));if ($ratio < 1) {    $targetWidth = $targetHeight * $ratio;} else {    $targetHeight = $targetWidth / $ratio;}$srcWidth = $originalWidth;$srcHeight = $originalHeight;$srcX = $srcY = 0;

This crops the image to fill the target size completely, not stretching it:

$targetWidth = $targetHeight = min($originalWidth, $originalHeight, $size);if ($ratio < 1) {    $srcX = 0;    $srcY = ($originalHeight / 2) - ($originalWidth / 2);    $srcWidth = $srcHeight = $originalWidth;} else {    $srcY = 0;    $srcX = ($originalWidth / 2) - ($originalHeight / 2);    $srcWidth = $srcHeight = $originalHeight;}

And this does the actual resizing:

$targetImage = imagecreatetruecolor($targetWidth, $targetHeight);imagecopyresampled($targetImage, $originalImage, 0, 0, $srcX, $srcY, $targetWidth, $targetHeight, $srcWidth, $srcHeight);

In this case the $size is just one number for both width and height (square target size). I'm sure you can modify it to use non-square targets. It should also give you an inspiration on what other resizing algorithms you can use.


$ratio = $originalWidth / $originalHeight

if you want to change the Height:

$targetWidth = $targetHeight * $ratio

if you want to change the Width:

$targetHeight = $targetWidth / $ratio


What you want is to maintain the aspect ratio of your original image. This is the ratio between the width and the height of the image. So you calculate the factor by which you have to resize the image in the vertical and horizontal direction and then you keep the higher of the two. In pseudocode:

target_height = 768target_width = 1024# v_fact and h_fact are the factor by which the original vertical / horizontal# image sizes should be multiplied to get the image to your target size.v_fact = target_height / im_height h_fact = target_width / im_width# you want to resize the image by the same factor in both vertical # and horizontal direction, so you need to pick the correct factor from# v_fact / h_fact so that the largest (relative to target) of the new height/width# equals the target height/width and the smallest is lower than the target.# this is the lowest of the two factorsim_fact = min(v_fact, h_fact)new_height = im_height * im_factnew_width = im_width * im_factimage.resize(new_width, new_height)