你的代码的问题是
$file_name
对所有图像都一样。另外,您没有获得正确的图像资源。以下是工作解决方案:
<?php
if (!empty($_POST)) {
$newname = md5(rand() * time());
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
sleep(1);
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
$filename = $_FILES["files"]["name"][$key];
if ($file_type == "image/gif") {
$sExt = ".gif";
} elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
$sExt = ".jpg";
} elseif ($file_type == "image/png" || $file_type == "image/x-png") {
$sExt = ".png";
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "upload/";
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700);
}
if (move_uploaded_file($file_tmp, $desired_dir . $file_name . $sExt)) {
$uploadedFiles[$key] = array($file_name . $sExt, 1);
} else {
echo "Couldn't upload file " . $_FILES['files']['name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
}
} else {
print_r($errors);
}
}
function compress($filename, $destination, $quality) {
$info = getimagesize($filename);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($filename);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($filename);
} elseif($info['mime'] == 'image/png') {
$image = imagecreatefrompng($filename);
}else{
$image =null;
}
return imagejpeg($image, $destination, $quality);
}
$compressed = 0;
$destination_img = 'compressed/';
foreach($uploadedFiles as $km=>$val){
$photos = $desired_dir . $val[0];
$compressed += compress($photos, $destination_img.$val[0], 60);
}
if($compressed>=1){
echo $compressed.' Images compresses';
}else{
echo 'No Image Compressed';
}
}
}
?>
<form method="POST" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="file" name="files[]">File 1<br>
<input type="file" name="files[]">File 2<br>
<input type="file" name="files[]">File 3<br>
<input type="submit" name="filesubmit" value="Submit">
</form>
请检查以下链接以更好地了解图像处理和生成的方式:
-
imagejpeg()
-
getimagesize()
我希望我的回答对你有帮助。