使用PHP调整图像大小

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用PHP调整图像大小相关的知识,希望对你有一定的参考价值。

To use the resize function you must pass in the forced width, forced height, source image, and destination image. The function then uses the GD2 library functions to read the source image's size. It will then calculate the new image's size based off of the forced width and height. This function will maintain the original image's aspect ratio so your image won't look distorted. It won't change the source image at all but when the function is done running you will end up with the destination image which is resized to the dimensions you passed into the function. As far as I know, this function requires the GD2 library although you might be able to get it to work with the GD1 library. The GD library extension must be enabled in php before you can use GD2 functions so keep that in mind as well. You can use the PHP function phpinfo() to see if GD2 is enabled or to see what version of the GD library your server is using.
  1. <?php
  2. function resampimagejpg( $forcedwidth, $forcedheight, $sourcefile, $destfile )
  3. {
  4. $fw = $forcedwidth;
  5. $fh = $forcedheight;
  6. $is = getimagesize( $sourcefile );
  7. if( $is[0] >= $is[1] )
  8. {
  9. $orientation = 0;
  10. }
  11. else
  12. {
  13. $orientation = 1;
  14. $fw = $forcedheight;
  15. $fh = $forcedwidth;
  16. }
  17. if ( $is[0] > $fw || $is[1] > $fh )
  18. {
  19. if( ( $is[0] - $fw ) >= ( $is[1] - $fh ) )
  20. {
  21. $iw = $fw;
  22. $ih = ( $fw / $is[0] ) * $is[1];
  23. }
  24. else
  25. {
  26. $ih = $fh;
  27. $iw = ( $ih / $is[1] ) * $is[0];
  28. }
  29. $t = 1;
  30. }
  31. else
  32. {
  33. $iw = $is[0];
  34. $ih = $is[1];
  35. $t = 2;
  36. }
  37. if ( $t == 1 )
  38. {
  39. $img_src = imagecreatefromjpeg( $sourcefile );
  40. $img_dst = imagecreatetruecolor( $iw, $ih );
  41. imagecopyresampled( $img_dst, $img_src, 0, 0, 0, 0, $iw, $ih, $is[0], $is[1] );
  42. if( !imagejpeg( $img_dst, $destfile, 90 ) )
  43. {
  44. exit( );
  45. }
  46. }
  47. else if ( $t == 2 )
  48. {
  49. copy( $sourcefile, $destfile );
  50. }
  51. }
  52. ?>

以上是关于使用PHP调整图像大小的主要内容,如果未能解决你的问题,请参考以下文章

使用 PHP 调整图像大小

使用gd在php中调整图像大小后的黑色背景

在 PHP 中调整图像大小

php imagick调整图像代码无法正常工作

php调整图像大小然后裁剪图像问题

这个调整图像大小/裁剪图像的逻辑是不是正确(在 php 中,但它是关于逻辑而不是代码)