Создание превьюшек для изображений
define('FILESDIR', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR);
if (!empty($_POST) && !empty($_FILES))
{
$error = array();
$extensions = array('png', 'jpg', 'jpeg', 'gif');
$fname = $_FILES['file']['name'];
$fname_ext = explode('.', $fname);
/* Проверка расширения */
if (count($fname_ext) != 2)
{
$error[] = 'file must have one extension';
}
else
{
$ext = $fname_ext[1];
}
if (!in_array($ext, $extensions))
{
$error[] = lng('err_file_ext_2') . ' ' . implode(', ', $extensions);
}
$fname = strtolower($fname);
if (preg_match("/[^\da-z_\-.]+/", $fname))
{
$error[] = 'file name must have only the next symbols: a-z, 0-9, _-.';
}
$fname = FILESDIR . $fname_ext[0] . '.' . $ext;
/* Проверка файла на существование */
if (file_exists($fname))
{
$fname_ext[0] .= '_' . time();
$fname = FILESDIR . $fname_ext[0] . '.' . $ext;
}
if (empty($error))
{
/* Загружаем файл */
if (copy($_FILES['file']['tmp_name'], $fname) === TRUE)
{
/* Создаем превью для изображения */
if (extension_loaded('gd'))
{
$imageSize = getimagesize($fname);
$types = array(1 => 'gif', 2=> 'jpg', 3 => 'png');
$imageType = array_key_exists($imageSize[2], $types) ? $types[$imageSize[2]] : FALSE;
if ($imageType !== FALSE)
{
$width = $imageSize[0];
$height = $imageSize[1];
if ($width > 220 || $height > 176)
{
switch ($imageType)
{
case 'gif':
$image = imagecreatefromgif($fname);
break;
case 'jpg':
$image = imagecreatefromjpeg($fname);
break;
case 'png':
$image = imagecreatefrompng($fname);
break;
default:
}
$max = $width > $height ? 'w' : 'h';
$new_width = 176;
$new_height = 220;
if ($max == 'w' && $width > $new_width)
{
$new_height = intval(($new_width * $height) / $width);
}
if ($max == 'h' && $height > $new_height)
{
$new_width = intval(($new_height * $width) / $height);
}
$preview = imagecreate($new_width, $new_height);
imagecopyresized($preview, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagepng($preview, FILESDIR . $fname_ext[0] . '_preview.png');
var_dump($width, $height, $new_width, $new_height);
}
}
}
$_SESSION['libFiles'] += 1;
$_SESSION['files'][$fname_ext[0] . '.' . $ext] = $_FILES['file']['type'];
echo '<div class="gmenu">File uploaded. <a href="index.php">Repeat</a></div>';
}
else
{
$error[] = 'Unable to load file';
}
}
}
else
{
echo '<form action="index.php" method="post" enctype="multipart/form-data">' .
'Choose file:<br /><input type="file" name="file" />' .
'<input type="submit" name="submit" value="Upload" /></form>' .
'<p><a href="?show">Show uploaded images</a></p>';
}
if (isset($_GET['show']))
{
$dir = scandir(FILESDIR);
unset($dir[0], $dir[1]);
foreach ($dir as $img)
{
echo '<hr />' . $img . '<br /><img src="./img/' . $img . '" alt="" /><hr />';
}
}
if (!empty($error))
{
echo implode('<br />', $error) . '<br /><a href="index.php">Continue</a>';
}