Saturday, August 29, 2009

PHP scale_to function to scale a series of values such as an image or video height and width

Need to scale a series of values based on one of the values in proportion to a master value. This is good if you have an image or video that you want to display in proportion, but at a larger or smaller scale.

Parameter one is an array of numeric values such as: $dims = array(100,75);
The first index may be width and the second the height of an image, but this function will accept an unlimited amount of indexes.

Parameter two is the master value to use when creating the scale ratio: $master_value = 1000;

Parameter three is the index of of the array $dims that the function will use to create the master ratio: $master_value_index = 0;

scale_to(array(100,75),1000,0); would return an array with the values (1000,750). Since the ratio of the specified master index is 10 to 1, 75, and any other values besides the master value are all multiplied by 10.


function scale_to($dims,$master_value,$master_value_index)

if(!is_array($dims))return false;
if(!is_int($master_value))return false;
$master_value_index>count($dims)-1)return false;

$ratio = $master_value / $dims[$master_value_index];

foreach($dims as $k=>$v)

$new_dims[$k] = $master_value_index == $k ?$master_value : round($dims[$k] * $ratio);


return $new_dims;