>我有一个简单的多图像上传脚本,可以调整图像大小以保持纵横比。调整大小工作正常。但是,即使语法正确,我似乎也无法将图像发送到正确的文件夹。
简而言之,这是我正在做的事情:
如果文件输入"图像"不为空,则在"../company_images" 创建的文件夹的名称是由"$photo_目录_名称"变量定义的 Uniqid。在此之后,为每个图像运行调整大小函数,然后将调整大小的图像放入由"$total_path"变量定义的上传文件夹中。
if(!empty($_FILES["Image"])){
$photo_directory_name = uniqid(rand(100, 1000));
$photos_path = "company_images/" . $photo_directory_name;
$directory = "../company_images/";
if (!file_exists($directory . $photo_directory_name)) {
$upload_dir = mkdir($directory . $photo_directory_name, 0777, TRUE);
}else{
$upload_dir = $directory . $photo_directory_name;
}
function resize($width, $height){
/* Get original image x y*/
list($w, $h) = getimagesize($_FILES['Image']['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 = $width.'x'.$height.'_'.$_FILES['Image']['name'];
$total_path = $directory . $photo_directory_name . $path;
/* read binary data from image file */
$imgString = file_get_contents($_FILES['Image']['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image,
0, 0,
$x, 0,
$width, $height,
$w, $h);
/* Save image */
switch ($_FILES['Image']['type']) {
case 'image/jpeg':
imagejpeg($tmp, $total_path, 100);
break;
case 'image/png':
imagepng($tmp, $total_path, 0);
break;
case 'image/gif':
imagegif($tmp, $total_path);
break;
default:
exit;
break;
}
return $total_path;
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}
$max_file_size = 1024*1000; // 1mb
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
// thumbnail sizes
$sizes = array(1200 => 1000);
if ($_SERVER['REQUEST_METHOD'] == 'POST' AND isset($_FILES['Image'])) {
if( $_FILES['Image']['size'] < $max_file_size ){
// get file extension
$ext = strtolower(pathinfo($_FILES['Image']['name'], PATHINFO_EXTENSION));
if (in_array($ext, $valid_exts)) {
/* resize image */
foreach ($sizes as $w => $h) {
$files[] = resize($w, $h);
}
} else {
$response["message"] = 'photos_invalid_format';
$errors++;
}
} else{
$response["message"] = 'photos_file_too_large';
$errors++;
}
}
echo $total_path;
}
任何帮助都非常感谢。谢谢
您在调整大小函数中使用了一些全局变量:
$directory
$photo_directory_name
它们需要作为参数传入,或者在该函数中声明为全局变量:
function resize($width, $height){
global $directory, $photo_directory_name;
// rest of function