我有一个简单的表单,您可以在其中选择要上传到文件夹的图像。字面上只包含input type="file"
。我的目的是允许用户上传图像文件,然后将它们调整到指定的高度和宽度,同时明智地做到这一点,因此调整大小和裁剪不是巨大图像的角落。
这样用户就不必担心预先格式化他们的图像
我在PHP文档页面上看到了这个函数来调整图像大小
/**
* Resize an image and keep the proportions
* @author Allison Beckwith <allison@planetargon.com>
* @param string $filename
* @param integer $max_width
* @param integer $max_height
* @return image
*/
function resizeImage($filename, $max_width, $max_height)
{
list($orig_width, $orig_height) = getimagesize($filename);
$width = $orig_width;
$height = $orig_height;
# taller
if ($height > $max_height) {
$width = ($max_height / $height) * $width;
$height = $max_height;
}
# wider
if ($width > $max_width) {
$height = ($max_width / $width) * $height;
$width = $max_width;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0,
$width, $height, $orig_width, $orig_height);
return $image_p;
}
然后我在下面有这个脚本将未剪切的图像移动到文件夹
if(isset($_POST['submit']))
{
$test = is_writable("test");
echo "The directory 'test' returned $test";
echo "<br>";
echo "<br>";
$name = $_FILES['file']['name'];
$name = str_replace('..', '', $name);
$name = str_replace('/', '', $name);
$name = str_replace('\\', '', $name);
// Get file information and set paths
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
$tempname = $_FILES['file']['tmp_name'];
$imagePath = "images/";
$thumbPath = "images/thumbs/";
// Array of allowed types
$allowed_file_type = array(
"image/jpeg",
"image/jpg",
"image/gif",
"image/png"
);
if (!in_array($type, $allowed_file_type))
{
echo "Type is: $type";
echo "This file type is not allowed";
}
else if($size > 8000000)
{
echo "Files can only be up to 8MB";
}
else{
if(!is_dir($imagePath))
{
mkdir($imagePath, 0777, true);
}
if(!is_dir($thumbPath))
{
mkdir($thumbPath, 0777, true);
}
/* if(is_dir($imagePath)){
echo "$imagePath was created on the server";
echo "<br>";
echo "<br>";
}
else{
echo "$imagePath was not created on the server";
echo "<br>";
echo "<br>";
} */
if(move_uploaded_file($tempname, $imagePath.$name))
{
echo "Stored in: $imagePath$name";
$crop = resizeImage($name, 370, 370);
echo imagepng($crop);
}
else{
echo "Something went wrong";
}
}
}
图像移动后,我可以使用裁剪功能裁剪刚刚上传的图像,然后将该图像移动到另一个文件夹吗?
$crop = resizeImage($name, 370, 370);
if(move_uploaded_file($crop, $thumbPath.$name))
{
}
else{
}
基本上我有一个/images
文件夹,在其中我有一个/thumbs
文件夹,以防万一用户因任何原因想要原件回来。
如有必要,我可以提供更详细的代码。
我可能正在咆哮错误的树,所以如果有更简单或更直接的方法,我会感兴趣。鉴于最合适的答案,我显然会改进我的问题,以便帮助其他人。