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:
- Resize image proportionally with CSS
- How to auto-resize an image to fit a div container using CSS?
- How to resize an image in an HTML 5 canvas ?
- JPEG Full Form
- CSS | resize Property
- How to Resize Rotation Radius using CSS ?
- Nodejs | GM resize() Function
- Node Jimp | resize
- Resize an iframe based on the content
- HTML | DOM Style resize Property
- Convert an image into grayscale image using HTML/CSS
- How to hide “Image not found” icon when source image is not found?
- ES6 | Image Map
- CSS | Image Sprites
- How to darken an Image using CSS ?
- Saving an Image from URL in PHP
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.