我尝试在一个目录中调整所有图像的大小。我的代码工作,直到我尝试调整70张图片的目录。我已经使用了imagedestroy和unset。但我仍然失败了“致命错误:允许内存大小67108864字节耗尽(试图分配17232字节)”。(我的php内存设置为64M,无法修改)
$file = scandir ( $dir );
foreach ( $file as $key => $filename ) {
$src = $dir . '/' . $filename;
$dst = $dir . '/' . $filename;
$width = 660; // max width
$height = 2000; // max height
$message = image_resize ( $src, $dst, $width, $height, $crop = 0 );
if ($message == 1)
echo "$filename resize success!";
else
echo "$filename $message";
}
function image_resize($src, $dst, $width, $height, $crop = 0) {
if (! list ( $w, $h ) = getimagesize ( $src ))
return "Unsupported picture type!";
$type = strtolower ( substr ( strrchr ( $src, "." ), 1 ) );
if ($type == 'jpeg')
$type = 'jpg';
switch ($type) {
case 'bmp' :
$img = imagecreatefromwbmp ( $src );
break;
case 'gif' :
$img = imagecreatefromgif ( $src );
break;
case 'jpg' :
$img = imagecreatefromjpeg ( $src );
break;
case 'png' :
$img = imagecreatefrompng ( $src );
break;
default :
return "Unsupported picture type!";
}
// resize
if ($crop) {
if ($w < $width or $h < $height) {
imagedestroy ( $img );
unset ( $img );
return "Picture is too small!";
}
$ratio = max ( $width / $w, $height / $h );
$h = $height / $ratio;
$x = ($w - $width / $ratio) / 2;
$w = $width / $ratio;
} else {
if ($w < $width and $h < $height) {
imagedestroy ( $img );
unset ( $img );
return "Picture is too small!";
}
$ratio = min ( $width / $w, $height / $h );
$width = $w * $ratio;
$height = $h * $ratio;
$x = 0;
}
$new = imagecreatetruecolor ( $width, $height );
// preserve transparency
if ($type == "gif" or $type == "png") {
imagecolortransparent ( $new, imagecolorallocatealpha ( $new, 0, 0, 0, 127 ) );
imagealphablending ( $new, false );
imagesavealpha ( $new, true );
}
imagecopyresampled ( $new, $img, 0, 0, $x, 0, $width, $height, $w, $h );
switch ($type) {
case 'bmp' :
imagewbmp ( $new, $dst );
break;
case 'gif' :
imagegif ( $new, $dst );
break;
case 'jpg' :
imagejpeg ( $new, $dst );
break;
case 'png' :
imagepng ( $new, $dst );
break;
}
imagedestroy ( $img );
imagedestroy ( $new );
unset ( $img );
unset ( $new );
return true;
}