图像缩放在限制范围内(最大高度最大宽度)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了图像缩放在限制范围内(最大高度最大宽度)相关的知识,希望对你有一定的参考价值。

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.
  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. }

以上是关于图像缩放在限制范围内(最大高度最大宽度)的主要内容,如果未能解决你的问题,请参考以下文章

使用 CSS 将 div 内的图像向上和/或向下缩放以适应图像的最大边

JS等比例缩放图片,限定最大宽度和最大高度

使用 PHP 缩放图像并保持纵横比

在 IE 上获取图像加载时的图像宽度失败

CSS 和图像大小

Pooling Layer:池化层