我将尝试回答您的问题:
问题 1
那部分其实很简单。要创建文件上传表单,您的 HTML 需要如下所示:
<form enctype='multipart/form-data' action='CodeTool.php' method='POST'>
File: <input name='picture' type='file'/>
<input type='submit' value='Upload'/>
</form>
您的表格需要拥有enctype='multipart/form-data'
并且method
需要POST
。然后,要读取上传文件,您可以简单地使用以下内容。我还添加了一些基本验证以确保文件是图像。
if(isset($_FILES['picture'])) {
echo "File has been uploaded under temp file " . $_FILES['picture']['tmp_name'];
// Let's check if the file is an image:
$fileData = file_get_contents($_FILES['picture']['tmp_name']);
// Using imagecreatefromstring, that way you don't need to
// guess the image format.
if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
echo " and is a valid image";
} else {
echo " and is not a valid image";
}
}
问题2
要创建缩略图,您可以使用 GD(或 ImageMagick,但它不包含在默认配置中)这样......让我们继续imagecreatefromstring
if
声明:
if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
// Let's create a 100x100 thumbnail
$width = imagesx($img);
$height = imagesy($img);
$boxSize = min($width,$height);
$boxX = ($width / 2) - ($boxSize / 2);
$boxY = ($height / 2) - ($boxSize / 2);
$thumb = imagecreatetruecolor(100, 100);
imagecopyresampled($thumb, $img, 0, 0, $boxX, $boxY, 100, 100, $boxSize, $boxSize);
//$thumb is now a 100x100 thumbnail
}
问题 3
在这里,您有 2 个选项。您可以将图像存储在文件系统或数据库中。要将图像存储在文件系统中,您可以执行以下操作:
if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
move_uploaded_file($_FILES['picture']['tmp_file'], 'somefile.jpg');
// the code from the previous example
imagejpeg($thumb, 'somefile_thumb.jpg');
}
我个人更喜欢使用数据库来存储图像,因为它更容易保持引用完整性并使备份更简单(备份数据库就完成了)。它有点慢,但差异真的不是很大:
if(($img = @imagecreatefromstring($fileData)) !== FALSE) {
// the code from the previous example
$tmp_thumb = tempnam(sys_get_temp_dir(), 'thumb');
imagejpeg($thumb, $tmp_thumb);
$thumbData = file_get_contents($tmp_thumb);
mysql_query("INSERT INTO images (original, thumb) VALUES ('" . mysql_real_escape_string($fileData) . "', '" . mysql_real_escape_string($thumbData) . "');");
}
字段必须是BLOB
.