黑马程序员技术交流社区

标题: 【上海校区】上传图片封装(含自动生成缩略图) [打印本页]

作者: 爱编码的J    时间: 2019-4-26 09:45
标题: 【上海校区】上传图片封装(含自动生成缩略图)
一. 在项目的制作过程中上传的图片有大图片和缩小版的图片一起上传到服务器上,如何实现上传一张图片之后,缩小版的图片也会在服务器中保存,可以将图片的缩放封装成函数,在以后的实际开发中直接调用
[PHP] 纯文本查看 复制代码
<?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]);
        }






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2