Why do we need to resize images?
In a website, often, we need to scale an image to fit a particular section. Sometimes, it becomes necessary to scale down any image of random size to fit a cover photo section or profile picture section. Also, we need to show a thumbnail of a bigger image. In those cases, it’s not feasible to manually resize the image always.
One way to solve the above problem is to use the following method where we need to just set the width and height attributes on the image tag in our HTML.
<img src="check.jpg" height="100" width="100" alt="Image resize">
The problem with this is that the entire image is downloaded from the server and it is shown in the decreased size within the browser. This means the same amount of bandwidth is required to show the image in the smaller size that would have been required in case of the original size.
Using PHP to resize the image on server end: We will be henceforth using PHP to decrease the image dimension and render it so that a smaller size is only downloaded on the client end and not the original image. To achieve this we will be using the imagecopyresampled() function in PHP.
The imagecopyresampled() function is used to copy and resize an image or part of the image with resampling.
bool imagecopyresampled( resource $dst_image, resource $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_w, int $dst_h, int $src_w, int $src_h )
Parameters: This function accepts a rectangular area from $src_image of width $src_w and height $src_h at position ($src_x, $src_y) and place it in a rectangular area of $dst_image of width $dst_w and height $dst_h at position ($dst_x, $dst_y).
Example: This example uses imagecopyresampled() function to resize the image.
- Original Image:
- Output Image: