0
如何使用php调整文件夹中的图像大小?如何使用php调整文件夹中的图像大小?
我尝试使用此代码来调整图像的大小$imgPath ="test_images/english-728b1414843000.png";
到200x200 px
,但不工作,我该怎么做?
<?php
function resize($width, $height, $imgPath, $nm){
/* Get original image x y*/
list($w, $h) = getimagesize($_FILES[$nm]['tmp_name']);
/* calculate new image size with ratio */
$ratio = max($width/$w, $height/$h);
$h = ceil($height/$ratio);
$x = ($w - $width/$ratio)/2;
$w = ceil($width/$ratio);
/* new file name */
$path = $imgPath;
/* read binary data from image file */
$imgString = file_get_contents($_FILES[$nm]['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
//$nm = imagecreatetruecolor(400, 300);
imagealphablending($tmp, FALSE);
imagesavealpha($tmp, TRUE);
imagecopyresampled($tmp, $image,
0, 0,
$x, 0,
$width, $height,
$w, $h);
/* Save image */
switch ($_FILES[$nm]['type']) {
case 'image/jpeg':
imagejpeg($tmp, $path, 100);
break;
case 'image/png':
imagepng($tmp, $path, 0);
break;
case 'image/gif':
imagegif($tmp, $path);
break;
default:
exit;
break;
}
return $path;
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}
?>
<?PHP
$imgPath ="test_images/english-728b1414843000.png";
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
// thumbnail sizes
$sizes = array(200 => 200);
$ext = strtolower(pathinfo($_FILES[$nm]['name'], PATHINFO_EXTENSION));
if (in_array($ext, $valid_exts)) {
/* resize image */
foreach ($sizes as $w => $h) {
$files[] = resize($w, $h, $imgPath ,$nm);
}
}
?>