批量遍历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;
}
}
}
如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。
如本文对您有用,捐赠和留言 将是对我最好的支持~(捐赠可转为站内积分)
如愿意,请向朋友推荐本站,谢谢。
尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。