Images are zoomed in and out by comparison. This function is implemented using the gd library function in the php Tutorial. We will use imagecreatetruecolor () and imagecopyresampled () for operations.
Function my_image_resize ($ src_file, $ dst_file, $ dst_width = 32, $ dst_height = 32 ){
If ($ dst_width <1 | $ dst_height <1 ){
Echo "params width or height error! ";
Exit ();
}
If (! File_exists ($ src_file )){
Echo $ src_file. "is not exists! ";
Exit ();
}
$ Type = exif_imagetype ($ src_file );
$ Support_type = array (imagetype_jpeg, imagetype_png, imagetype_gif );
If (! In_array ($ type, $ support_type, true )){
Echo "this type of image does not support! Only support jpg, gif or png ";
Exit ();
}
Switch ($ type ){
Case imagetype_jpeg:
$ Src_img = imagecreatefromjpeg ($ src_file );
Break;
Case imagetype_png:
$ Src_img = imagecreatefrompng ($ src_file );
Break;
Case imagetype_gif:
$ Src_img = imagecreatefromgif ($ src_file );
Break;
Default:
Echo "load image error! ";
Exit ();
}
$ Src_w = imagesx ($ src_img );
$ Src_h = imagesy ($ src_img );
$ Ratio_w = 1.0 * $ dst_width/$ src_w;
$ Ratio_h = 1.0 * $ dst_height/$ src_h;
If ($ src_w <= $ dst_width & $ src_h <= $ dst_height ){
$ X = ($ dst_width-$ src_w)/2;
$ Y = ($ dst_height-$ src_h)/2;
$ New_img = imagecreatetruecolor ($ dst_width, $ dst_height );
Imagecopy ($ new_img, $ src_img, $ x, $ y, 0, $ dst_width, $ dst_height );
Switch ($ type ){
Case imagetype_jpeg:
Imagejpeg ($ new_img, $ dst_file, 100 );
Break;
Case imagetype_png:
Imagepng ($ new_img, $ dst_file );
Break;
Case imagetype_gif:
Imagegif ($ new_img, $ dst_file );
Break;
Default:
Break;
}
} Else {
$ Dstwh = $ dst_width/$ dst_height;
$ Srcwh = $ src_w/$ src_h;
If ($ ratio_w <= $ ratio_h ){
$ Zoom_w = $ dst_width;
$ Zoom_h = $ zoom_w * ($ src_h/$ src_w );
} Else {
$ Zoom_h = $ dst_height;
$ Zoom_w = $ zoom_h * ($ src_w/$ src_h );
}
$ Zoom_img = imagecreatetruecolor ($ zoom_w, $ zoom_h );
Imagecopyresampled ($ zoom_img, $ src_img, 0, 0, 0, $ zoom_w, $ zoom_h, $ src_w, $ src_h );
$ New_img = imagecreatetruecolor ($ dst_width, $ dst_height );
$ X = ($ dst_width-$ zoom_w)/2;
$ Y = ($ dst_height-$ zoom_h)/2 + 1;
Imagecopy ($ new_img, $ zoom_img, $ x, $ y, 0, $ dst_width, $ dst_height );
Switch ($ type ){
Case imagetype_jpeg:
Imagejpeg ($ new_img, $ dst_file, 100 );
Break;
Case imagetype_png:
Imagepng ($ new_img, $ dst_file );
Break;
Case imagetype_gif:
Imagegif ($ new_img, $ dst_file );
Break;
Default:
Break;
}
}
}
To sum up, we need to generate a scale to generate a small graph and use $ dstwh = $ dst_width/$ dst_height;
$ Srcwh = $ src_w/$ src_h; judge and generate.