php 等比例缩小图片

本文章收藏了四款关于利用php等比例缩小图片代码函数,我们可定义图片宽度或高度对图片缩小或放大的图片宽度,好了看看四款实例那一款适合于你吧.

php 等比例缩小图片实例代码如下:

  1. function imageresize2($width, $height, $targetw, $targeth)
  2. {
  3. $percentage = 1;
  4. if (($width > $targetw) || ($height > $targeth))
  5. {
  6. $width_diff = $width - $targetw;
  7. $height_diff = $height - $targeth;
  8. if ($width_diff >= $height_diff)
  9. {
  10. $percentage = ($targetw / $width);
  11. }
  12. else
  13. {
  14. $percentage = ($targeth / $height);
  15. }
  16. }
  17. //gets the new value and applies the percentage, then rounds the value
  18. $width = round($width * $percentage);
  19. $height = round($height * $percentage);
  20. $resize[0] = $width;
  21. $resize[1] = $height;
  22. return $resize;
  23. }
  24. //方法二
  25. if (!$max_width)
  26. $max_width = 240;
  27. if (!$max_height)
  28. $max_height = 200;
  29. $size = getimagesize($image);
  30. $width = $size[0];
  31. $height = $size[1];
  32. $x_ratio = $max_width / $width;
  33. $y_ratio = $max_height / $height;
  34. if ( ($width <= $max_width) && ($height <= $max_height) ) {
  35. $tn_width = $width;
  36. $tn_height = $height;
  37. }
  38. else if (($x_ratio * $height) < $max_height) {
  39. $tn_height = ceil($x_ratio * $height);
  40. $tn_width = $max_width;
  41. }
  42. else {
  43. $tn_width = ceil($y_ratio * $width);
  44. $tn_height = $max_height;
  45. }
  46. $src = imagecreatefrompng($image);
  47. $dst = imagecreate($tn_width,$tn_height);
  48. imagecopyresized($dst, $src, 0, 0, 0, 0,
  49. $tn_width,$tn_height,$width,$height);
  50. header("content-type: image/png");
  51. imagepng($dst, null, -1);
  52. imagedestroy($src);
  53. imagedestroy($dst);
  54. //方法三
  55. /*
  56. 函数原型如下:
  57. 参数说明:
  58. $oldwidth:原图片宽度
  59. $oldheight:原图片高度
  60. $imgwidth:缩小或放大的图片宽度
  61. $imgheight:缩小或放大的图片高度
  62. 返回:wwww.phpfensi.com
  63. 数组:arraysize ,其中索引为:width 和height 即:arraysize['width']、arraysize['height']
  64. */
  65. function getimgsize($oldwidth,$oldheight,$imgwidth,$imgheight)
  66. {
  67. //$oldwidth设置的宽度,$oldheight设置的高度,$imgwidth图片的宽度,$imgheight图片的高度;
  68. //单元格装得能装得进图片,则按图片的真实大小显示;
  69. if($imgwidth<=$oldwidth&&$imgheight<=$oldheight)
  70. {
  71. $arraysize=array('width'=>$imgwidth,'height'=>$imgheight);
  72. return $arraysize;
  73. }
  74. else
  75. {
  76. $suoxiaowidth=$imgwidth-$oldwidth;
  77. $suoxiaoheight=$imgheight-$oldheight;
  78. $suoxiaoheightper=$suoxiaoheight/$imgheight;
  79. $suoxiaowidthper=$suoxiaowidth/$imgwidth;
  80. if($suoxiaoheightper>=$suoxiaowidthper)
  81. {
  82. //单元格高度为准;
  83. $aftersuoxiaowidth=$imgwidth*(1-$suoxiaoheightper);
  84. $arraysize=array('width'=>$aftersuoxiaowidth,'height'=>$oldheight);
  85. return $arraysize;
  86. }
  87. else
  88. {
  89. //单元格宽度为准;
  90. $aftersuoxiaoheight=$imgheight*(1-$suoxiaowidthper);
  91. $arraysize=array('width'=>$oldwidth,'height'=>$aftersuoxiaoheight);
  92. return $arraysize;
  93. }
  94. }
  95. }