Skip to content

Instantly share code, notes, and snippets.

@hanseartic
Last active November 10, 2015 22:15
Show Gist options
  • Save hanseartic/a1329ce612d42d3c0702 to your computer and use it in GitHub Desktop.
Save hanseartic/a1329ce612d42d3c0702 to your computer and use it in GitHub Desktop.
calculate image (re)size and keep ratio
<?php
class ImgTools
{
/**
* Calculate image dimensions from given ratio and desired new x-/y- values
*
* @param int $desired_width desired image width
* @param int $desired_height desired image height
* @param int $ratio desired ratio
* @param bool $new_values_are_maximum true if the resulting image should not be larger in any dimension (max size),
* false if the image should have at least the given size (min size)
* @return array containing new x and y values matching the ratio
* @throws \RuntimeException
*/
public static function calculateImageSize($desired_width, $desired_height, $ratio, $new_values_are_maximum = true)
{
if (empty($ratio))
{
throw new \RuntimeException('Image ratio cannot be 0.');
}
$width = $desired_width;
$height = $desired_height;
if (empty($width))
{
$width = $height * $ratio;
}
elseif (empty($height))
{
$height = $width / $ratio;
}
if ($new_values_are_maximum) $width = $height * $ratio;
else $height = $width / $ratio;
if ($height > $desired_height == $new_values_are_maximum)
{
$width = $width / $height * $desired_height;
$height = $desired_height;
}
elseif ($width > $desired_width == $new_values_are_maximum)
{
$height = $height / $width * $desired_width;
$width = $desired_width;
}
return [$width, $height];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment