/** * Center crop picture * @param string $source [Original path] * @param int $width [set width] * @param int $height [Set height] * @param string $targ ET [Target path] * @return bool [crop result]*/function Image_center_crop ($source, $width, $height, $target) {if(!file_exists ($source))return false; /*loading images by type*/ Switch(Exif_imagetype ($source)) { Caseimagetype_jpeg: $image=imagecreatefromjpeg ($source); Break; Caseimagetype_png: $image=imagecreatefrompng ($source); Break; Caseimagetype_gif: $image=imagecreatefromgif ($source); Break; } if(!isset ($image))return false; /*Get image size information*/$target _w=$width; $target _h=$height; $source _w=Imagesx ($image); $source _h=Imagesy ($image); /*Calculate crop width and height*/$judge= (($source _w/$source _h) > ($target _w/$target _h)); $resize _w= $judge? ($source _w * $target _h)/$source _h: $target _w; $resize _h=! $judge? ($source _h * $target _w)/$source _w: $target _h; $start _x= $judge? ($resize _w-$target _w)/2:0; $start _y=! $judge? ($resize _h-$target _h)/2:0; /*Draw Center Zoom image*/$resize _img=Imagecreatetruecolor ($resize _w, $resize _h); Imagecopyresampled ($resize _img, $image,0,0,0,0, $resize _w, $resize _h, $source _w, $source _h); $target _img=Imagecreatetruecolor ($target _w, $target _h); Imagecopy ($target _img, $resize _img,0,0, $start _x, $start _y, $resize _w, $resize _h); /*save a picture to a file*/ if(!file_exists (DirName ($target))) mkdir (DirName ($target),0777,true); Switch(Exif_imagetype ($source)) { Caseimagetype_jpeg:imagejpeg ($target _img, $target); Break; Caseimagetype_png:imagepng ($target _img, $target); Break; Caseimagetype_gif:imagegif ($target _img, $target); Break; } returnBoolval (file_exists ($target));}
Center clipping function for PHP images