上传图片封装(含自动生成缩略图)

227 阅读1分钟
一.
在项目的制作过程中上传的图片有大图片和缩小版的图片一起上传到服务器上
,
如何实现上传一张图片之后
,
缩小版的图片也会在服务器中保存
,
可以将图片的缩放封装成函数
,
在以后的实际开发中直接调用
[PHP]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
/*
*缩放函数
*@param string $path 图片的路径
*@param int $width 缩放的宽度
*@param int $height 缩放的高度
*@param string $savePath 保存文件的路径
*/
function thumb($path,$width,$height,$savepath="./thumb"){
//获取图片的宽高
$size=getimagesize($path);
//设置dswidth和dsheight为图片的实际宽高
list($dswidth,$dsheight)=$size;
//获取到宽高的比例
$scale=min($dswidth/$dsheight,$dsheight/$dswidth);
if($dswidth>$dsheight){
$mapwidth=$width;
$mapheight=$height*$scale;
}else{
$mapheight=$height;
$mapwidth=$width*$scale;
}
//创建画布资源
$img=imagecreatetruecolor($mapwidth,$mapheight);
//获取文件类型
$ext=getimagesize($path)["mime"]; //image/jpeg
$ext2=substr($ext,strrpos($ext,"/")+1);
//生成图片函数imagecreatefromjpeg()
$open="imagecreatefrom".$ext2;
//生成图片imagejpeg()
$save="image".$ext2;
//打开图片
$img2=$open($path);
//对图片进行缩放
imagecopyresampled($img,$img2,0,0,0,0,$mapwidth,$mapheight,$dswidth,$dsheight);
//将传进来的文件夹路径设置格式工整
$pathdir=rtrim($savepath,"/")."/";
//生成文件名
$filename=uniqid().time()."_".$width."_".".".$ext2;
//生成最终的文件名
$fullpath=$pathdir.$filename;
//保存图片
$save($img,$fullpath);
//销毁资源
imagedestroy($img);
imagedestroy($img2);
}
$arr=[
[600,600],
[500,500],
[400,400],
[300,300]
];
foreach($arr as $v){
thumb("./images/flower.jpg",$v[0],$v[1]);
}