设为首页 收藏本站
查看: 706|回复: 0

[经验分享] PHP中面向对象的图片处理类

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2016-9-23 09:02:58 | 显示全部楼层 |阅读模式
      我们对图片的处理主要是添加水印和等比缩放,在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
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
<?php

/**
*图片处理
*/
class Image
{
    //路径
    private $path = './upload/';
    //随机文件名
    private $isRandName;


    //初始化成员方法
    public function __construct($path = null , $r = true)
    {
        if (!is_null($path)) {
            $this->path = rtrim($path,'/').'/';
        }
        $this->isRandName = $r;
    }

    //water水印的方法
    //源(图片 $dst)  目标(水印 $src)  位置(9宫格) 前缀($prefix) 透明度($tmd )
    public function water($dst,$src,$pos = 9,$prefix = 'wa_', $tmd = 100)
    {
        //判断文件路径是否存在
        $src = $this->path . $src;
        if (!file_exists($dst) || !file_exists($src)) {
            exit('图片或者水印不存在');
        }

        //获取图像(图片和水印)的相关信息
        $dstInfo = self::getImageInfo($dst);
        $srcInfo = self::getImageInfo($src);
        //var_dump($dstInfo);
        //判断宽高是否超过了目标图片的宽高
        if (!$this->_checkSize($dstInfo,$srcInfo)) {
            exit('水印图片的宽、高不合法');
        }

        //摆放位置  1 2 3 4 5 6 7 8 9 九宫格(3行3列)
        $postion = self::getPostion($dstInfo,$srcInfo,$pos);

        //打开图片
        $dstRes = self::openImage($dst,$dstInfo);
        $srcRes = self::openImage($src,$srcInfo);

        //将两个图片合并在一起  通过两张图片信息将图片合并在一起  需要自定义一个方法
        $newRes = $this->_mergeImage($dstRes,$srcRes,$postion,$dstInfo,$srcInfo,$tmd);

        //判断是否允许随机命名【保存之前】
        if ($this->isRandName) {

            //路径 前缀 产生id .  后缀
            //uniqid() 获取一个带前缀、基于当前时间微秒数的唯一ID
            $path = $this->path.$prefix . uniqid(). '.' .$dstInfo['subfix'];
        } else {

            //路径 前缀 文件原名
            $path = $this->path.$prefix . $dstInfo['basename'];
        }
        //保存图片
        self::saveImage($newRes,$path,$dstInfo);

        //销毁资源
        imagedestroy($dstRes);
        imagedestroy($srcRes);
        //返回路径

    }

    //等比缩放
    //源图片 宽 高 前缀
    public function thump($dst,$width,$height,$prefix = 'thump_')
    {
        //判断文件是否存在

        if (!file_exists($dst)) {
            exit('文件路径不存在');
        }

        //获取图像的信息  没有信息就退出
        $info = self::getImageInfo($dst);
        //得到一个新的尺寸
        $newSize = self::getNewSize($width,$height,$info);
        //打开资源
        $res = self::openImage($dst,$info);
        //等比缩放这个资源  处理gif背景变黑的问题
        $newRes = self::kidOfImage($res,$newSize,$info);
        //保存
        $path = $this->path.$prefix.$info['basename'];
        self::saveImage($newRes,$path,$info);
        //销毁资源
        imagedestroy($newRes);
        //返回路径
        return $path;

    }

    //等比缩放处理
    private static function kidOfImage($srcImg, $size, $imgInfo)
    {
        $newImg = imagecreatetruecolor($size["width"], $size["height"]);
        $otsc = imagecolortransparent($srcImg);
        if ( $otsc >= 0 && $otsc < imagecolorstotal($srcImg)) {
             $transparentcolor = imagecolorsforindex( $srcImg, $otsc );
                 $newtransparentcolor = imagecolorallocate(
                 $newImg,
                 $transparentcolor['red'],
                     $transparentcolor['green'],
                 $transparentcolor['blue']
             );

             imagefill( $newImg, 0, 0, $newtransparentcolor );
             imagecolortransparent( $newImg, $newtransparentcolor );
        }

        imagecopyresized( $newImg, $srcImg, 0, 0, 0, 0, $size["width"], $size["height"], $imgInfo["width"], $imgInfo["height"] );
        imagedestroy($srcImg);
        return $newImg;
    }

    //得到一个新的尺寸
    private static function getNewSize($width, $height, $imgInfo)
    {
        $size["width"] = $imgInfo["width"];   //将原图片的宽度给数组中的$size["width"]
        $size["height"] = $imgInfo["height"];  //将原图片的高度给数组中的$size["height"]

        if($width < $imgInfo["width"]) {
            $size["width"] = $width;             //缩放的宽度如果比原图小才重新设置宽度
        }

        if ($width < $imgInfo["height"]) {
            $size["height"] = $height;            //缩放的高度如果比原图小才重新设置高度
        }

        if($imgInfo["width"]*$size["width"] > $imgInfo["height"] * $size["height"]) {
            $size["height"] = round($imgInfo["height"] * $size["width"] / $imgInfo["width"]);
        } else {
            $size["width"] = round($imgInfo["width"] * $size["height"] / $imgInfo["height"]);
        }

        return $size;
    }


    //获取图片的相关信息
    public static function getImageInfo($path)
    {
        $data = [];
        //获取图片大小
        $info = getimagesize($path);
        //var_dump($info);
        //根据打印出来的信息 将键所对应的值(文件的大小)赋值给data的数组中
        $data['width'] = $info[0];
        $data['height'] = $info[1];
        $data['mime'] = $info['mime'];
        //获取路径  后缀 文件名信息
        $path = pathinfo($path);
        //var_dump($path);die;
        //根据打印出来的信息 将将键所对应的值(路径和文件名)赋值给data的数组中
        $data['basename'] = $path['basename'];
        $data['subfix'] = $path['extension'];

        return $data;

    }
    //检查图片和水印的宽高
    //将图片的宽高和水印的宽高进行比较
    private function _checkSize($dstInfo,$srcInfo)
    {
        //水印的宽应该小于图片的宽度或者水印的高度应该小于图片的高度 ,只要其中一个不满足就不能继续
        if ($dstInfo['width'] < $srcInfo['width'] || $dstInfo['height'] < $srcInfo['height']) {
            return false;
        }
        return true;
    }

    //位置处理
    public static function getPostion($dstInfo,$srcInfo,$pos)
    {
        switch ($pos) {
            case 1:
                $x = 0;
                $y = 0;
                break;
            case 2:
                $x = ceil(($dstInfo['width'] - $srcInfo['width']) / 2 );
                $y = 0;
                break;
            case 3:
                $x = $dstInfo['width'] - $srcInfo['width'];
                $y = 0;
                break;
            case 4:
                $x = 0;
                $y = ceil(($dstInfo['height'] - $srcInfo['height']) / 2 );
                break;
            case 5:
                $x = ceil(($dstInfo['width'] - $srcInfo['width']) / 2 );
                $y = ceil(($dstInfo['height'] - $srcInfo['height']) / 2 );
                break;
            case 6:
                $x = $dstInfo['width'] - $srcInfo['width'];
                $y = ceil(($dstInfo['height'] - $srcInfo['height']) / 2 );
                break;
            case 7:
                $x = 0;
                $y = $dstInfo['height'] - $srcInfo['height'];
                break;
            case 8:
                $x = ceil(($dstInfo['width'] - $srcInfo['width']) / 2 );
                $y = $dstInfo['height'] - $srcInfo['height'];
                break;
            case 9:
                $x = $dstInfo['width'] - $srcInfo['width'];
                $y = $dstInfo['height'] - $srcInfo['height'];
                break;
        }

        return ['x' => $x ,'y' =>$y];

    }

    //打开图片
    //根据图片的类型打开相应的图片资源
    private function openImage($path,$info)
    {
        switch ($info['mime']) {
            case 'image/png':
            case 'image/x-png':
                    $res = imagecreatefrompng($path);
                    break;
            case 'image/jpeg':
            case 'image/jpg':
            case 'image/pjpeg':

                    $res = imagecreatefromjpeg($path);
                    break;
            case 'image/gif':
                    $res = imagecreatefromgif($path);
                    break;
            case 'image/wbmp':
            case 'image/bmp':
                    $res = imagecreatefromwbmp($path);
                    break;
        }
        //var_dump($res);die;
        return $res;

    }

    //合并图片 imagecopymerge(图片,水印,图片坐标x,图片坐标y,水印坐标x,水印坐标y,透明度)
    private function _mergeImage($dstRes,$srcRes,$postion,$dstInfo,$srcInfo,$tmd)
    {

        imagecopymerge($dstRes,$srcRes,$postion['x'],$postion['y'],0,0,$srcInfo['width'],$srcInfo['height'],$tmd);
        return $dstRes;
    }

    //保存图片处理方法
    //参数:需要保存的图片资源,保存的路径,保存的信息
    public static function saveImage($res,$path,$info)
    {
        //根据不同的图片类型选择不同的函数进行保存
        switch ($info['mime']) {
            case 'image/png':
            case 'image/x-png':
                    imagepng($res,$path);
                    break;
            case 'image/jpeg':
            case 'image/jpg':
            case 'image/pjpeg':
                    imagejpeg($res,$path);
                    break;
            case 'image/gif':
                    imagegif($res,$path);
                    break;
            case 'image/wbmp':
            case 'image/bmp':
                    imagewbmp($res,$path);
                    break;
        }

    }
}




测试代码:
1
2
3
4
5
6
$img = new Image();
/*
$img->water('ly.png','logo.gif',3);
$img->water('ly.png','logo.gif',4);*/

$img->thump('ly.png',100,100,'l1_');






运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-276213-1-1.html 上篇帖子: PHP failed to ptrace(PEEKDATA) pid 1918: Input/output error (5)或者 increa... 下篇帖子: 解决PHP scandir()异常返回空问题 图片处理
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表