How to Resize an image in PHP?

Share This Post

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);


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?


Related Posts

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img