PHP CLASS TO CREATE IMAGE THUMBANILS

Some years ago, I wrote a PHP class to create image thumbnails because I needed it for a project. There were needed certain things that I could not able to find in other PHP classes, and I decided to create one with my specific needs. Today, after some improvements and fixes to perfect it, I have decided to share it with anyone that wants to use it.

Features of this class:

  • It is possible to work with the main image formats (jpg, png, and gif).
  • It is possible to resize images setting a width or a height and maintaining the original proportion.
  • It is possible to crop the images to a custom size maintaining its original proportion (it is also possible to chose the cropping position).
  • It is possible to store the resulting image in the server.
  • Is is possible to show the image in the browser on the fly.
  • It is possible to keep the alpha channel of PNG and GIFs images.

This class needs the GD library installed in the server (included in PHP from version 4.3)

  1 class Thumb {
2
3 private $image;
4 private $type;
5 private $mime;
6 private $width;
7 private $height;
8
9 //---读取图像的方法
10 public function loadImage($name) {
11
12 //---存储图像尺寸
13 $info = getimagesize($name);
14
15 $this->width = $info[0];
16 $this->height = $info[1];
17 $this->type = $info[2];
18 $this->mime = $info['mime'];
19
20 //---根据原始格式创建新图像
21 switch($this->type){
22
23 case IMAGETYPE_JPEG:
24 $this->image = imagecreatefromjpeg($name);
25 break;
26
27 case IMAGETYPE_GIF:
28 $this->image = imagecreatefromgif($name);
29 break;
30
31 case IMAGETYPE_PNG:
32 $this->image = imagecreatefrompng($name);
33 break;
34
35 default:
36 trigger_error('It is not possible to create a thumbnail using the specified format', E_USER_ERROR);
37
38 }
39
40 }
41
42 //---存储图像的方法
43 public function save($name, $quality = 100, $type = false) {
44
45 //---如果格式不存在,请选择原始图像的格式 46 $type = ($type) ? $type : $this->type;
 47         //---使用正确的格式存储图像
48 switch($type){
49
50 case IMAGETYPE_JPEG:
51 imagejpeg($this->image, $name . image_type_to_extension($type), $quality);
52 break;
53
54 case IMAGETYPE_GIF:
55 imagegif($this->image, $name . image_type_to_extension($type));
56 break;
57
58 case IMAGETYPE_PNG:
59 $pngquality = floor($quality / 100 * 9);
60 imagepng($this->image, $name . image_type_to_extension($type), $pngquality);
61 break;
62 default:
63 trigger_error('The specified image format is not correct', E_USER_ERROR);
64 }
65 }
66 //---即时显示图像的方法
67 public function show($type = false, $base64 = false) {
68
69 //---如果格式不存在,请选择原始图像的格式
70 $type = ($type) ? $type : $this->type;
71 if($base64) ob_start();
72
73 //---使用正确的格式显示图像
74 switch($type){
75 case IMAGETYPE_JPEG:
76 imagejpeg($this->image);
77 break;
78
79 case IMAGETYPE_GIF:
80 imagegif($this->image);
81 break;
82
83 case IMAGETYPE_PNG:
84 $this->prepareImage($this->image);
85 imagepng($this->image);
86 break;
87
88 default:
89 trigger_error('The specified image format is not correct', E_USER_ERROR);
90 exit;
91 }
92
93 if($base64) {
94 $data = ob_get_contents();
95 ob_end_clean ();
96 return 'data:' . $this->mime . ';base64,' . base64_encode($data);
97 }
98
99 }
100
101 //---按比例调整图像大小的方法
102 public function resize($value, $prop){
103
104 //---确定resize属性
105 $prop_value = ($prop == 'width') ? $this->width : $this->height;
106 $prop_versus = ($prop == 'width') ? $this->height : $this->width;
107
108 //---Determine the opposite resize property
109 $pcent = $value / $prop_value;
110 $value_versus = $prop_versus * $pcent;
111
112 //---使用resize属性创建图像
113 $image = ($prop == 'width') ? imagecreatetruecolor($value, $value_versus) : imagecreatetruecolor($value_versus, $value);
114
115 //---Treat the image
116 if($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG) $this->prepareImage($image);
117
118 //---制作一张考虑了resize属性的图像副本
119 switch($prop){
120 case 'width':
121 imagecopyresampled($image, $this->image, 0, 0, 0, 0, $value, $value_versus, $this->width, $this->height);
122 break;
123
124 default:
125 imagecopyresampled($image, $this->image, 0, 0, 0, 0, $value_versus, $value, $this->width, $this->height);
126 }
127
128 //---Update the image and its dimensions
129 $this->width = imagesx($image);
130 $this->height = imagesy($image);
131 $this->image = $image;
132 }
133
134 //---Method to extract a portion of the image maintaining its proportion
135 public function crop($cwidth, $cheight, $pos = 'center') {
136
137 $pcent = min($this->width / $cwidth, $this->height / $cheight);
138 $bigw = (int) ($pcent * $cwidth);
139 $bigh = (int) ($pcent * $cheight);
140
141 //---Create the image
142 $image = imagecreatetruecolor($cwidth, $cheight);
143
144 //---Treat the image
145 if($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG) $this->prepareImage($image);
146
147 //---Depending of the crop position
148 switch($pos){
149
150 case 'left':
151 imagecopyresampled($image, $this->image, 0, 0, 0, abs(($this->height - $bigh) / 2), $cwidth, $cheight, $bigw, $bigh);
152 break;
153
154 case 'right':
155 imagecopyresampled($image, $this->image, 0, 0, $this->width - $bigw, abs(($this->height - $bigh) / 2), $cwidth, $cheight, $bigw, $bigh);
156 break;
157
158 case 'top':
159 imagecopyresampled($image, $this->image, 0, 0, abs(($this->width - $bigw) / 2), 0, $cwidth, $cheight, $bigw, $bigh);
160 break;
161
162 case 'bottom':
163 imagecopyresampled($image, $this->image, 0, 0, abs(($this->width - $bigw) / 2), $this->height - $bigh, $cwidth, $cheight, $bigw, $bigh);
164 break;
165
166 default:
167 imagecopyresampled($image, $this->image, 0, 0, abs(($bigw - $this->width) / 2), abs(($bigh - $this->height) / 2), $cwidth, $cheight, $bigw, $bigh);
168 }
169 $this->width = $cwidth;
170 $this->height = $cheight;
171 $this->image = $image;
172 }
173 //---Private method to treat the images before show them
174 private function prepareImage($image){
175 //---Depending on the image type
176 switch($this->type){
177 case IMAGETYPE_GIF:
178 $background = imagecolorallocate($image, 0, 0, 0);
179 imagecolortransparent($image, $background);
180 break;
181
182 case IMAGETYPE_PNG:
183 imagealphablending($image, FALSE);
184 imagesavealpha($image, TRUE);
185 break;
186 }
187 }
188 }

Public methods

//Reads the image from the specified path
loadImage(string $name)
$name Image path
//Stores the image in the specified path
save(string $name [, int $quality = 100] [, int $type = false])
$name Image path
$quality Image quality with a value between 0 and 100
$type Image type defined by a constant IMAGETYPE_XXX (IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF). It is optional, if it is not sent, the original format will be used
// Shows the image directly on the page or returns a base64 representation of it
show([int $type = false] [,boolean $base64 = false])
$type Image type defined by a constant IMAGETYPE_XXX (IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF). It is optional, if it is not sent, the original format will be used
$base64 Specifies if the image flow should be printed on the page or should be returned as a base64.
//Resizes the image maintaining its proprtion
resize(int $value, string $reference)
$value The value of width or height that should be used to resize the image
$reference String that defines if the image should be resized taking into account the with or the height (possible values: ‘width’ or ‘height’)
//Crops the image creating a thumbnail of it
crop(int $width, int $height [, string $position = 'center'])
$width Width of the thumbnail
$height Height of the thumbnail
$position The position from which the thumbnail should be extracted (possible values: ‘top’, ‘right’, ‘bottom’, ‘left’ or ‘center’)

效果图:

PHP 图片裁切的更多相关文章

  1. Javascript图片裁切

    最近浏览了不少网站的图片裁切效果,大部分的做法如下图所示(借用一张脚本之家的图片),通过改变裁切框的大小来选取合适的位置. 但本文介绍的是另外一种裁切方式,裁切框由开发者决定,图片大小由用户决定,通过 ...

  2. Android实现图片裁切

    介绍 在应用开发中,如果涉及到个人信息,头像一般是不可避免的,类似这种情况,我们就需要用到图片裁切的功能,实现头像裁切,然后上传给服务器. 一般裁切的做法就是图层叠加选取框,然后根据坐标,计算裁切区域 ...

  3. 图片裁切插件jCrop的使用心得(三)

    在这一篇里,我来具体讲讲代码该如何写. 下面是jCrop的初始化代码 //图片裁剪插件Jcrop初始化 function initJcrop() { // 图片加载完成 document.getEle ...

  4. 图片裁切插件jCrop的使用心得(二)

    上一篇简单的介绍了一下开发的背景以及一些学习资料,下面开始介绍如何上手. 一.下载jCrop http://deepliquid.com/content/Jcrop_Download.html 直接去 ...

  5. html5手势操作与多指操作封装与Canvas图片裁切实战

    当前情况,移动端的开发占比越来越高,单指的拖拽触碰等操作是常规需要.特殊的多指操作与手势操作还需另做处理,而且还涉及到兼容性问题. // 屏幕上存在两根或两根以上的手指 时触发 仅IOS存在手势事件, ...

  6. js图片裁切

    js的图片裁切只支持移动和右下拉 html部分 <div id="box" class="box"> <img class="img ...

  7. thinkphp + 美图秀秀api 实现图片裁切上传,带数据库

    思路: 1.数据库 创建test2 创建表img,字段id,url,addtime 2.前台页: 1>我用的是bootstrap 引入必要的js,css 2>引入美图秀秀的js 3.后台: ...

  8. 图片裁切插件jCrop的使用心得(四)

    在本篇中我来介绍一下jcrop如何实时展现用户裁切的效果图以及在项目中使用该插件注意的问题. 首先,你们在创建头像时,都可以在旁边实时的看到我裁切后的效果图,就如博客园. 这个是如何实现的呢,其实并不 ...

  9. 图片裁切插件jCrop的使用心得(一)

    之前,项目经理为了提升用户体验让我在之前图片上传功能的基础上实现图片的裁切功能,作为一个前端小白来说听了这个需求心里一紧,毕竟没有做过,于是跟项目经理商量要先做下调研.在一上午的调研中发现了jCrop ...

  10. 05、Windows Store app 的图片裁切(更新)

    在 Win Phone Silverlight api 中,有一个 PhotoChooserTask 选择器,指定宽.高属性,在选择图片的时候, 可以进行裁切,代码: PhotoChooserTask ...

随机推荐

  1. ASP.NET MVC4获取当前系统时间

    <p>当前时间是:@ViewBag.CurrentDate.ToLongDateString()</p>

  2. 搭建邮件服务器 使用Postfix与Dovecot

    首先需要从yum中下载安装三个服务:bind-chroot    postfix     dovecot 配置文件依次: /etc/named.conf 下载安装完后要开启的服务:named     ...

  3. python随机生成个人信息

    python随机生成个人信息 #!/usr/bin/env python3 # -*- coding:utf-8 -*- import sys import random class Personal ...

  4. 别再说你不会ElasticSearch调优了,都给你整理好了

    ES 发布时带有的默认值,可为 ES 的开箱即用带来很好的体验.全文搜索.高亮.聚合.索引文档 等功能无需用户修改即可使用,当你更清楚的知道你想如何使用 ES 后,你可以作很多的优化以提高你的用例的性 ...

  5. WPF多线程更新UI的一个解决途径

    那么该如何解决这一问题呢?通常的做法是把耗时的函数放在线程池执行,然后切回主线程更新UI显示.前面的updateTime函数改写如下: private async void updateTime()  ...

  6. K8S操作

    一.K8Spods操作 kubectl delete all --all //删除 所有pods

  7. Linux 核心编译与管理

    一般情况下,不需要重新编译核心,除非以下特有的用途 [root@localhost ~]# wget ftp://ftp.twaren.net/pub/Unix/Kernel/linux/kernel ...

  8. (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape 错误

    使用网页版jupyder在读取桌面文件时,刚开始我的代码是: baseball = pd.read_csv('C:\Users\TuZhiqiang\Desktop\result.csv')print ...

  9. Codeforces 362E 费用流

    题意及思路:https://blog.csdn.net/mengxiang000000/article/details/52472696 代码: #define Hello the_cruel_wor ...

  10. RecyclerView跳转到指定位置的三种方式

    自从android5.0推出RecyclerView以后,RecyclerView越来越受广大程序员的热爱了!大家都知道RecyclerView的出现目的是为了替代listview和ScrollVie ...