批量遍历jpg并裁剪到400*400,代码在下面,自己看:

<?php
ini_set('memory_limit', '-1');
$files=glob("./img/*.jpg");
foreach($files as $f){
my_image_resize($f,$f,400,400);
}
function my_image_resize($src_file, $dst_file , $new_width , $new_height) {
if($new_width <1 || $new_height <1) {
echo "params width or height error !";
return;
}
if(!file_exists($src_file)) {
echo $src_file . " is not exists !";
return;
}
$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";
return;
}
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!";
return;
}
$w=imagesx($src_img);
$h=imagesy($src_img);
$ratio_w=1.0 * $new_width / $w;
$ratio_h=1.0 * $new_height / $h;
$ratio=1.0;
if( ($ratio_w < 1 && $ratio_h < 1) || ($ratio_w > 1 && $ratio_h > 1)) {
if($ratio_w < $ratio_h) {
$ratio = $ratio_h ;
}else {
$ratio = $ratio_w ;
}
$inter_w=(int)($new_width / $ratio);
$inter_h=(int) ($new_height / $ratio);
$inter_img=imagecreatetruecolor($inter_w , $inter_h);
imagecopy($inter_img, $src_img, 0,0,0,0,$inter_w,$inter_h);
$new_img=imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($new_img,$inter_img,0,0,0,0,$new_width,$new_height,$inter_w,$inter_h);
switch($type) {
case IMAGETYPE_JPEG : imagejpeg($new_img, $dst_file,100);
break;
case IMAGETYPE_PNG : imagepng($new_img,$dst_file,100);
break;
case IMAGETYPE_GIF : imagegif($new_img,$dst_file,100);
break;
default: break;
}
}else{
$ratio=$ratio_h>$ratio_w? $ratio_h : $ratio_w;
$inter_w=(int)($w * $ratio);
$inter_h=(int) ($h * $ratio);
$inter_img=imagecreatetruecolor($inter_w , $inter_h);
imagecopyresampled($inter_img,$src_img,0,0,0,0,$inter_w,$inter_h,$w,$h);
$new_img=imagecreatetruecolor($new_width,$new_height);
imagecopy($new_img, $inter_img, 0,0,0,0,$new_width,$new_height);
switch($type) {
case IMAGETYPE_JPEG : imagejpeg($new_img, $dst_file,100);
break;
case IMAGETYPE_PNG : imagepng($new_img,$dst_file,100);
break;
case IMAGETYPE_GIF : imagegif($new_img,$dst_file,100);
break;
default: break;
}
}
}

Related Posts: PHP-批量裁剪图片 :