3. improved code:
/*
* $ O_photo source image path
* $ D_photo: Path of the processed image
* $ Width defines the width.
* $ Height defines the height.
* Call method cutphoto ("test.jpg", "temp.jpg", 256,146 );
*/
Function cutphoto ($ o_photo, $ d_photo, $ width, $ height ){
$ Temp_img = imagecreatefromjpeg ($ o_photo );
$ O_width = imagesx ($ temp_img); // Obtain the source image width.
$ O_height = imagesy ($ temp_img); // obtain the original image height.
// Determine the processing method
If ($ width> $ o_width | $ height> $ o_height) {// The size of the source image width or height ratio is small and compressed.
$ Newwidth = $ o_width;
$ Newheight = $ o_height;
If ($ o_width> $ width ){
$ Newwidth = $ width;
$ Newheight = $ o_height * $ width/$ o_width;
}
If ($ newheight> $ height ){
$ Newwidth = $ newwidth * $ height/$ newheight;
$ Newheight = $ height;
}
// Thumbnail
$ New_img = imagecreatetruecolor ($ newwidth, $ newheight );
Imagecopyresampled ($ new_img, $ temp_img, 0, 0, 0, $ newwidth, $ newheight, $ o_width, $ o_height );
Imagejpeg ($ new_img, $ d_photo );
Imagedestroy ($ new_img );
} Else {// The original image width and height are larger than the specified size and are cropped after compression.
If ($ o_height * $ width/$ o_width> $ height) {// first, make sure that the width is the same as the specified width. if the height is greater than the specified height, OK
$ Newwidth = $ width;
$ Newheight = $ o_height * $ width/$ o_width;
$ X = 0;
$ Y = ($ newheight-$ height)/2;
} Else {// otherwise, the specified height is the same and the width is adaptive.
$ Newwidth = $ o_width * $ height/$ o_height;
$ Newheight = $ height;
$ X = ($ newwidth-$ width)/2;
$ Y = 0;
}
// Thumbnail
$ New_img = imagecreatetruecolor ($ newwidth, $ newheight );
Imagecopyresampled ($ new_img, $ temp_img, 0, 0, 0, $ newwidth, $ newheight, $ o_width, $ o_height );
Imagejpeg ($ new_img, $ d_photo );
Imagedestroy ($ new_img );
$ Temp_img = imagecreatefromjpeg ($ d_photo );
$ O_width = imagesx ($ temp_img); // Obtain the thumbnail width.
$ O_height = imagesy ($ temp_img); // Obtain the Thumbnail height.
// Crop an image
$ New_imgx = imagecreatetruecolor ($ width, $ height );
Imagecopyresampled ($ new_imgx, $ temp_img, 0, 0, $ x, $ y, $ width, $ height, $ width, $ height );
Imagejpeg ($ new_imgx, $ d_photo );
Imagedestroy ($ new_imgx );
- }
- }
- ?>