If the uploaded image is scaled directly, the image deformation will occur, and the experience is definitely not good. The following provides a solution. to reduce the size and add white borders, you can see the following code to generate thumbnails after uploading images to a website. this is usually a very common function for the beautiful display of websites, thumbnails will be of the same size. for example, for a website recently developed by the author, the thumbnails must be 160x120. However, if the proportion of the uploaded image is different from that of the thumbnail, direct scaling will cause deformation of the image, which is definitely not a good experience. So I thought of a compromise, that is, the method of adding white edges after narrowing down.
SOURCE image, with a size of 600x366:
Finally generated:
The code is relatively long. The following is a simple example:
First, the source image is generated proportionally, and the width is not greater than 160, and the height is not greater than 120. For example, a thumbnail of 160x98 is displayed.
Create a 160x120 white background image and center the thumbnail generated in the previous step to this image.
The final code is as follows:
The code is as follows:
// Source image path, which can be a local file or remote image
$ Src_path = '1.jpg ';
// The width of the final saved image
$ Width = 160;
// The height of the final saved image
$ Height = 120;
// Source image object
$ Src_image = imagecreatefromstring (file_get_contents ($ src_path ));
$ Src_width = imagesx ($ src_image );
$ Src_height = imagesy ($ src_image );
// Generate a thumbnail with an equal proportion
$ Tmp_image_width = 0;
$ Tmp_image_height = 0;
If ($ src_width/$ src_height> = $ width/$ height ){
$ Tmp_image_width = $ width;
$ Tmp_image_height = round ($ tmp_image_width * $ src_height/$ src_width );
} Else {
$ Tmp_image_height = $ height;
$ Tmp_image_width = round ($ tmp_image_height * $ src_width/$ src_height );
}
$ TmpImage = imagecreatetruecolor ($ tmp_image_width, $ tmp_image_height );
Imagecopyresampled ($ tmpImage, $ src_image, 0, 0, 0, 0, $ tmp_image_width, $ tmp_image_height, $ src_width, $ src_height );
// Add white edges
$ Final_image = imagecreatetruecolor ($ width, $ height );
$ Color = imagecolorallocate ($ final_image, 255,255,255 );
Imagefill ($ final_image, 0, 0, $ color );
$ X = round ($ width-$ tmp_image_width)/2 );
$ Y = round ($ height-$ tmp_image_height)/2 );
Imagecopy ($ final_image, $ tmpImage, $ x, $ y, 0, 0, $ tmp_image_width, $ tmp_image_height );
// Output image
Header ('content-Type: image/jpeg ');
Imagejpeg ($ final_image );