PHP Image Ratio Width & Height, Top & Left


/ Published in: PHP
Save to your folder(s)

Returns array with information like:
Input image
width 200
height 200

print_r(ratioResize('path/to/image.ext' , 100 , 50));



output:


array(
[ratio] => .5,
[height] => 50,
[width] => 50,
[left] => 25,
[top] => 25
);


Copy this code and paste it in your HTML
  1. function ratioResize( $image , $maxwidth , $maxheight , $forcewidth=false ){
  2. $return = array();list( $w , $h ) = getimagesize( $image );
  3. if($w < $maxwidth && $h < $maxheight && !$forcewidth)return array('width'=>$w,'height'=>$h,'left'=>($maxwidth-$w)/2,'top'=>($maxheight-$h)/2,'ratio'=>1);
  4. $rw = $maxwidth/$w; $rh = $maxheight/$h; //GET HEIGHT AND WIDTH RATIO
  5. $return['ratio'] = $rw <= $rh?$rw:$rh;
  6. $return['height'] = round($h*($return['ratio']));
  7. $return['width'] = round($w*($return['ratio'])); //GET CALCULATED DIMENSIONS FROM RATIO
  8. $return['left'] = ($maxwidth - $return['width'])/2;
  9. $return['top'] = ($maxheight - $return['height'])/2;//GET CALCULATED CENTERING PIXELS
  10. return $return;
  11. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.