Resizing an Image Using PHP


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

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.


Copy this code and paste it in your HTML
  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. ?>

URL: http://www.netlobo.com/php_image_resize_gd2.html#

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.