引言
图片上传
准备工作
首先,确保你的服务器已经安装了PHP和GD库,GD库是PHP处理图像的重要组件。
创建上传表单
<form action="upload.php" method="post" enctype="multipart/form-data">
选择图片:<input type="file" name="image" />
<input type="submit" value="上传" />
</form>
PHP处理上传
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$image = $_FILES['image'];
$path = "prodimg/"; // 保存图片的文件夹路径
$maxFileSize = 200000; // 上传文件大小,单位BYTE
// 检查文件类型
$uptypes = array(
'image/jpg',
'image/jpeg',
'image/png',
'image/pjpeg',
'image/gif',
'image/bmp',
'image/x-png'
);
// 检查文件大小
if ($image['size'] > $maxFileSize) {
die("文件过大,请上传小于200KB的图片。");
}
// 检查文件类型
if (!in_array($image['type'], $uptypes)) {
die("不支持的文件类型。");
}
// 移动文件到指定路径
if (!move_uploaded_file($image['tmp_name'], $path . $image['name'])) {
die("上传失败。");
}
echo "图片上传成功。";
}
?>
缩略图生成
设置缩略图参数
在upload.php中设置缩略图的宽度和高度:
// 设置缩略图参数
$width = 150; // 缩略图宽度
$height = 150; // 缩略图高度
生成缩略图
<?php
// 生成缩略图
function createThumbnail($src, $path, $width, $height) {
list($srcWidth, $srcHeight) = getimagesize($src);
$srcRatio = $srcWidth / $srcHeight;
$dstRatio = $width / $height;
if ($srcRatio > $dstRatio) {
$newWidth = $width;
$newHeight = $width / $srcRatio;
} else {
$newHeight = $height;
$newWidth = $height * $srcRatio;
}
$srcImage = imagecreatefromjpeg($src);
$dstImage = imagecreatetruecolor($width, $height);
// 调整图片大小
imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
// 保存缩略图
imagejpeg($dstImage, $path . "thumbnail_" . $image['name']);
imagedestroy($dstImage);
imagedestroy($srcImage);
}
// 调用函数生成缩略图
createThumbnail($path . $image['name'], $path, $width, $height);
?>
完整代码示例
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$image = $_FILES['image'];
$path = "prodimg/";
$maxFileSize = 200000;
$width = 150;
$height = 150;
$uptypes = array(
'image/jpg',
'image/jpeg',
'image/png',
'image/pjpeg',
'image/gif',
'image/bmp',
'image/x-png'
);
if ($image['size'] > $maxFileSize) {
die("文件过大,请上传小于200KB的图片。");
}
if (!in_array($image['type'], $uptypes)) {
die("不支持的文件类型。");
}
if (!move_uploaded_file($image['tmp_name'], $path . $image['name'])) {
die("上传失败。");
}
echo "图片上传成功。";
// 生成缩略图
createThumbnail($path . $image['name'], $path, $width, $height);
}
?>