Site upload image after the generation of thumbnails should be very commonly used functions, usually for the site to show beautiful, thumbnails will be the same size, such as the recent author to do a site, thumbnail specifications are 160x120. But if the upload image scale and thumbnail inconsistent, direct scaling will cause the image distortion, so the experience is certainly bad. So I think of a compromise approach, is to reduce the addition of white edge method.
Source diagram, size is 600x366:
End-generated effect diagram:
The code is relatively long, the following simple idea:
The source diagram is generated proportionally to the thumbnail, and is not greater than 160, and the height is not greater than 120. For example, the image of Mr. 160x98 as a thumbnail image.
To create a new 160x120 white background picture, center the thumbnail generated in the previous step into this picture and OK.
The final code is as follows:
Copy Code code as follows:
The path to the source diagram, either a local file or a remote picture
$src _path = ' 1.jpg ';
Finally save the width of the picture
$width = 160;
Finally save the picture high
$height = 120;
Source Diagram Object
$src _image = imagecreatefromstring (file_get_contents ($src _path));
$src _width = imagesx ($src _image);
$src _height = Imagesy ($src _image);
Generate equal proportions of thumbnails
$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 Edge
$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 picture
Header (' Content-type:image/jpeg ');
Imagejpeg ($final _image);