Skip to content
Home » How to Resize an image in PHP?

How to Resize an image in PHP?

In this article, we are going to learn How to resize an image using PHP. I can resize images using PHP. This is not easy but not a hard task for every image can be resized using ImageMagick or GD functions.

Images can be resized using ImageMagick or GD functions. If GD’s functions are used, the image file size is also reduced when raw digital camera images are sampled.

What is the GD function in PHP?

The library of GD also allows you to create images from a string using the imagecreatefromstring() function in PHP. The imagecreatefromstring() function is an inbuilt function in PHP this is used to create a new image from a string file or URL please Remember that you will have to use base64_decode() on the given string before imagecreatefromstring().

How to Resize an image in PHP?

The function can spontaneously detect if the image type is PNG, JPG, GIF, and another supported format. Now we are going to see how does GD function work see below the code.

function image_resize($file_name, $width, $height, $crop=FALSE) {
   list($wid, $ht) = getimagesize($file_name);
   $r = $wid / $ht;
   if ($crop) {
      if ($wid > $ht) {
         $wid = ceil($wid-($width*abs($r-$width/$height)));
      } else {
         $ht = ceil($ht-($ht*abs($r-$w/$h)));
      }
      $new_width = $width;
      $new_height = $height;
   } else {
      if ($width/$height > $r) {
         $new_width = $height*$r;
         $new_height = $height;
      } else {
         $new_height = $width/$r;
         $new_width = $width;
      }
   }
   $source = imagecreatefromjpeg($file_name);
   $dst = imagecreatetruecolor($new_width, $new_height);
   image_copy_resampled($dst, $source, 0, 0, 0, 0, $new_width, $new_height, $wid, $ht);
   return $dst;
}
$img_to_resize = image_resize(‘path-to-jpg-image’, 250, 250);

READ MORE:

How to make a redirect in PHP?

How To Fix Undefined Index In PHP ( $_POST and $_GET )?

The Best Way to Strip Punctuation from a String using Python?

Leave a Reply

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