PHP 图片裁切
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 |
|
| $name | Image path |
//Stores the image in the specified path |
|
| $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 |
|
| $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 |
|
| $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 |
|
| $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 图片裁切的更多相关文章
- Javascript图片裁切
最近浏览了不少网站的图片裁切效果,大部分的做法如下图所示(借用一张脚本之家的图片),通过改变裁切框的大小来选取合适的位置. 但本文介绍的是另外一种裁切方式,裁切框由开发者决定,图片大小由用户决定,通过 ...
- Android实现图片裁切
介绍 在应用开发中,如果涉及到个人信息,头像一般是不可避免的,类似这种情况,我们就需要用到图片裁切的功能,实现头像裁切,然后上传给服务器. 一般裁切的做法就是图层叠加选取框,然后根据坐标,计算裁切区域 ...
- 图片裁切插件jCrop的使用心得(三)
在这一篇里,我来具体讲讲代码该如何写. 下面是jCrop的初始化代码 //图片裁剪插件Jcrop初始化 function initJcrop() { // 图片加载完成 document.getEle ...
- 图片裁切插件jCrop的使用心得(二)
上一篇简单的介绍了一下开发的背景以及一些学习资料,下面开始介绍如何上手. 一.下载jCrop http://deepliquid.com/content/Jcrop_Download.html 直接去 ...
- html5手势操作与多指操作封装与Canvas图片裁切实战
当前情况,移动端的开发占比越来越高,单指的拖拽触碰等操作是常规需要.特殊的多指操作与手势操作还需另做处理,而且还涉及到兼容性问题. // 屏幕上存在两根或两根以上的手指 时触发 仅IOS存在手势事件, ...
- js图片裁切
js的图片裁切只支持移动和右下拉 html部分 <div id="box" class="box"> <img class="img ...
- thinkphp + 美图秀秀api 实现图片裁切上传,带数据库
思路: 1.数据库 创建test2 创建表img,字段id,url,addtime 2.前台页: 1>我用的是bootstrap 引入必要的js,css 2>引入美图秀秀的js 3.后台: ...
- 图片裁切插件jCrop的使用心得(四)
在本篇中我来介绍一下jcrop如何实时展现用户裁切的效果图以及在项目中使用该插件注意的问题. 首先,你们在创建头像时,都可以在旁边实时的看到我裁切后的效果图,就如博客园. 这个是如何实现的呢,其实并不 ...
- 图片裁切插件jCrop的使用心得(一)
之前,项目经理为了提升用户体验让我在之前图片上传功能的基础上实现图片的裁切功能,作为一个前端小白来说听了这个需求心里一紧,毕竟没有做过,于是跟项目经理商量要先做下调研.在一上午的调研中发现了jCrop ...
- 05、Windows Store app 的图片裁切(更新)
在 Win Phone Silverlight api 中,有一个 PhotoChooserTask 选择器,指定宽.高属性,在选择图片的时候, 可以进行裁切,代码: PhotoChooserTask ...
随机推荐
- 2644. 数列 (Standard IO)
这道题是道数论题,如果想对了的话会很快. 因为这道题实在是没有什么知识点,所以我直接上代码,代码上有很详细的注释: #include<iostream> #include<cstdi ...
- vscode 配置 golang开发环境
如果你使用golang,那么强烈建议你采用vscode作为IDE. 1. 首先在vscode 当中安装go插件,如上图 2. 配置 %AppData%\Code\User\settings.json ...
- 使用matplotlib画出log的图像
以下内容是学习笔记,若有侵权,立即删除! import math import matplotlib.pyplot as plt import numpy as np if __name__ == ' ...
- Uncaught (in promise) DOMException谷歌浏览器js报错分析
Chrome的自动播放的政策在2018年4月做了更改,这点在开源中国的这篇文章中也有说到. 新的行为:浏览器为了提高用户体验,减少数据消耗,现在都在遵循autoplay政策,Chrome的autopl ...
- python3中装饰器的用法总结
装饰器预备知识点 1 函数赋值给一个变量 函数名可以像普通变量一样赋值给另一个变量. def test(): print("i am just a test function") ...
- 【题解】A Horrible Poem
题目大意 给出一个由小写英文字母组成的字符串 S,再给出 q 个询问,要求回答 S 某个子串的最短循环节. 如果字符串 B 是字符串 A 的循环节,那么 A 可以由 B 重复若干次得到. 输入格式 第 ...
- 1.etcd
etcd v3版接口命令 etcdctl --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/heal ...
- ASP.NET Core 2.1 JWT Token 使用 (二) - 简书
原文:ASP.NET Core 2.1 JWT Token 使用 (二) - 简书 接上文,https://www.jianshu.com/p/c5f9ea3b4b65 ASP.NET Core 2. ...
- Python之基本的日期与时间转换 datetime、 dateutil模块
简单举例datetime模块 from datetime import timedelta,datetime a = timedelta(days=2, hours=6) b = timedelta( ...
- 五、hibernate表与表之间的关系(一对多关系)
数据库表与表之间的关系 一对多:一个学校可以有多个学生,一个学生只能有一个学校 多对多:一个学生可以有多个老师,一个老师可以教多个学生 一对一:一个人只能有一个身份证号,一个身份证号只能找到一个人 一 ...