PHP image resizing with fixed height and width

PHP image resizing with fixed height and width

This function will resize images via php gd library.

<?
function Image($image, $maxWidth, $maxHeight, $padding = 0, $r = 255, $g = 255, $b = 255 )
{
 $image = ImageCreateFromString(file_get_contents($image));
 if (is_resource($image) === true)
 {
  $x = 0;
  $y = 0;
 
  $width = imagesx($image);
  $height = imagesy($image);
 
  $result = ImageCreateTrueColor($maxWidth, $maxHeight);
 
  $ratio = min( $maxWidth / $width, $maxHeight/ $height );
 
  $newWidth = $ratio * $width;
  $newHeight = $ratio * $height;
 
  $newWidth = $newWidth - $padding;
  $newHeight = $newHeight - $padding;
 
  $new_x = ($maxWidth - $newWidth) /2;
  $new_y = ($maxHeight - $newHeight) /2;
 
  ImageSaveAlpha($result, true);
  ImageAlphaBlending($result, true);
  ImageFill($result, 0, 0, ImageColorAllocate($result, $r, $g, $b));
  ImageCopyResampled($result, $image, $new_x, $new_y, $x, $y, $newWidth, $newHeight, $width, $height);
 
  ImageInterlace($result, true);
  ImageJPEG($result, null, 90);
 }
 
 return false;
}
header('Content-Type: image/jpeg');
Image('zzz.jpg', 500, 300, 5, 0, 0,0 );
?>

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *