PHP Image Resize picture resize function code
Last Update:2017-02-28
Source: Internet
Author: User
Copy Code The code is as follows:
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,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,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,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
}
}
}