名称:图片上传简易处理
描述:
1、前端页面做一个上传图片的表单(不需要样式和其他功能),上传任意一张图片(不限大小,不限格式);
2、服务端php接收这张图片,然后进行以下三个操作
1)将上传的这张原图保存到一个文件夹下;
2)将上传的这张图片缩放到特定尺寸300px200px,并将缩放后的图片保存到文件夹下;(即图片的拉伸、缩放);
3)截取这张原图的中心300px
200px区域,并将该区域保存成一张新图片放到文件夹下;

审核标准:前端上传一张任意图片,后端经过php接收处理后在对应的文件下生成三张图片,分别是原图、缩放的图、裁剪的图。

解决之道:

  • imagecreatefromjpeg — 由文件或 URL 创建一个新图象。
  • imagecreatetruecolor — 新建一个真彩色图像
  • getimagesize — 取得图像大小
  • imagecopyresampled — 重采样拷贝部分图像并调整大小
  • imagejpeg — 输出图象到浏览器或文件。

详见php手册

上代码:

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html lang="en" style="overflow-x:visible;">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="">
<meta name="keywords" content="">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body style="overflow-x:visible;">
<form action="index.php" enctype="multipart/form-data" method="post">
<label>仅支持jpg格式图片</label><br>
<input type="file" name="avatar" accept="image/png,image/jpg,image/jpeg,imge/bmp,image/gif">
<input type="submit" value="提交" name="">
</form>
</body>
</html>

index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
$image = $_FILES['avatar'];

if ($image['error'] == 4) {
echo "请选择图片!";
exit();
}
if($image['error'] == UPLOAD_ERR_OK) {
$dest='static/img/';
if (!file_exists('static/img')) {
mkdir('static/img', 0777, true);
}
// 保存完整图片
move_uploaded_file($image['tmp_name'], $dest.$image["name"]);

//保存缩放图
$src_image = imagecreatefromjpeg($dest.$image["name"]);
$dst_image = ImageCreateTrueColor(300, 200);
$src_image_w = getimagesize($dest.$image["name"])['0'];
$src_image_h = getimagesize($dest.$image["name"])['1'];
imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, 300, 200, $src_image_w, $src_image_h);
imagejpeg($dst_image, 'static/img/zoom_'.$image["name"], 100);

//保存截图
imagecopyresampled($dst_image, $src_image, 0, 0, $src_image_w/2-150, $src_image_h/2-100, 300, 200, 300, 200);
imagejpeg($dst_image, 'static/img/center_'.$image["name"], 100);

//TODO保存图片路径到库

echo "保存成功";
}

希望这篇文章能给你带来知识和乐趣,喜欢博主的文章可以加博主好友哦

有好的文章也可以向博主投稿哦