A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

一. 在项目的制作过程中上传的图片有大图片和缩小版的图片一起上传到服务器上,如何实现上传一张图片之后,缩小版的图片也会在服务器中保存,可以将图片的缩放封装成函数,在以后的实际开发中直接调用
[mw_shl_code=php,true]<?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]);
        }[/mw_shl_code]

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马