我将此代码保存在一个名为uploader.php的文件中。我从另一个文件中调用此文件来上传图像,效果很好。在相册中,我看不到缩略图(如果我上传的图像中包含()和[]字符,则它们为空白。我想在上传时删除类似的字符,或者让它们显示出来。
$maindir = "../alla_bilder/images/";
$maindir_th = "../alla_bilder/images/thumbs/";
$uploaddir = "images/";
$uploaddir_th = "images/thumbs/";
$allowed = array('jpg','jpeg','gif','png');
$max_size = 5048 * 1024;
while (list ($key, $val) = each ($_FILES))
{
if ($_FILES[$key]['size'] <= $max_size)
{
$file_ext = pathinfo($_FILES[$key]['name'],PATHINFO_EXTENSION);
$file_name = basename($_FILES[$key]['name'],'.'.$file_ext);
if (in_array(strtolower($file_ext),$allowed))
{
$name = $_FILES[$key]['name'];
$x = 1;
while (file_exists($uploaddir.'/'.$name))
{
$name = $file_name.'['.$x.'].'.$file_ext;
$x++;
}
if (move_uploaded_file($_FILES[$key]['tmp_name'],$uploaddir.'/'.$name))
{
chmod($uploaddir.'/'.$name, 0644);
}
else
{
die(error_get_last());
}
}
else
{
die("Invalid file type");
}
}
else
{
die("File size too big");
}
copy($uploaddir.'/'.$name, $maindir.'/'.$name);
$images = glob("images/thumbs/*.*");
foreach($images as $image)
{
$output .= '<div class="col-md-2" align="center" ><img src="' . $image .'" width="200px" height="140px" style="border:1px solid #ccc;" /></div>';
}
$modwidth = 200;
$modheight = 140;
list($width, $height) = getimagesize($uploaddir.'/'.$name);
$ratio_orig = $width/$height;
if ($width/$height > $ratio_orig)
{
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
$tn = imagecreatetruecolor($modwidth, $modheight);
//$image = imagecreatefromjpeg($uploaddir.'/'.$name);
$image = imagecreatefromstring(file_get_contents($uploaddir.'/'.$name));
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
imagejpeg($tn, $uploaddir_th.'/'.$name);
imagejpeg($tn, $maindir_th.'/'.$name);
}
//查看缩略图的代码:
$directory = 'images/';
$thumbsdir = 'images/thumbs';
$allowed_types = array('jpg', 'JPG', 'JPEG', 'jpeg', 'gif', 'PNG', 'png');
$fileNames = $files = $file_parts = array();
$ext = '';
/* $title = ''; */
$i = 0;
$toMatch = "{$directory}*.{".implode(',', $allowed_types).'}';
$fileNames = glob($toMatch, GLOB_NOSORT | GLOB_BRACE);
foreach($fileNames as $file) {
$f = explode('/', $file);
$fileName = end($f);
$files[$fileName] = filemtime($file);
}
arsort($files);
foreach(array_keys($files) as $file)
{
$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));
/* $title = implode('.',$file_parts);
$title = htmlspecialchars($title); */
echo '
<div class="pic " style="background:url('.$thumbsdir.'/'.$file.') no-repeat 50% 50%;">
<a href="'.$directory.'/'.$file.'" title="'.$title.'">'.$title.'</a>
</div>';
$i++;
}