Image Scaling within Limits (max height, max width)


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

This is a much cleaner way to do this than the number of examples on the web. Every example I saw seemed to account for orientation - horizontal vs. vertical vs. square when looking at the input. This ignores horizontal and vertical by mapping the "long side" and "short side" and then re-mapping the variables to $h / $w at the end.


Copy this code and paste it in your HTML
  1. function scale_dimensions_within_limits($w,$h,$max_w,$max_h){
  2. // $w is the width of the current rectangle
  3. // $h is the height of the current rectangle
  4. // $max_w is the maximum width that an image can be sized
  5. // $max_h is the maximum height that an image can be sized
  6.  
  7. // **** Here's where the magic is starts ****
  8. // Switch the concept of horiz/vertical/square to long/short side
  9. $short_side_len = ($w < $h ? $w : $h);
  10. $long_side_len = ($w > $h ? $w : $h);
  11. // Set a variable to the variable name of the output variable
  12. $ssvar = ($w > $h ? 'h':'w');
  13. $lsvar = ($w > $h ? 'w':'h');
  14. $maxLSvar = "max_".$lsvar;
  15. $maxSSvar = "max_".$ssvar;
  16.  
  17. // Do the first pass on the long side
  18. $ratio = $$maxLSvar/$long_side_len;
  19. $newSS = round($short_side_len * $ratio);
  20. $newLS = round($long_side_len * $ratio);
  21.  
  22. // *** Note - the only coditional block!
  23. // If short side is still out of limit, limit the short side and adjust
  24. if($newSS > $$maxSSvar){
  25. $ratio = $$maxSSvar/$newSS;
  26. $newLS = round($ratio*$newLS);
  27. $newSS = $$maxSSvar;
  28. }
  29.  
  30. // **** Here's where the magic ends ****
  31. // Re-couple the h/w (or w/h) with the long/shortside counterparts
  32. // $$ means it's a variable variable (dynamic assignment)
  33. $$ssvar = $newSS;
  34. $$lsvar = $newLS;
  35.  
  36. // Prep the return array
  37. $dimensions['w'] = $w; // this is derived from either $ssvar or $lsvar
  38. $dimensions['h'] = $h; return $dimensions;
  39. }

URL: http://davesthings.posterous.com/im-feeling-brilliant

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.