PageRenderTime 59ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/Core/ThinkPHP/Extend/Library/ORG/Util/Image.class.php

https://bitbucket.org/thinkphp/cms
PHP | 486 lines | 332 code | 27 blank | 127 comment | 85 complexity | 7c785808435a2461a38d81d3a4e6197b MD5 | raw file
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. /**
  12. * 图像操作类库
  13. * @category ORG
  14. * @package ORG
  15. * @subpackage Util
  16. * @author liu21st <liu21st@gmail.com>
  17. */
  18. class Image {
  19. /**
  20. * 取得图像信息
  21. * @static
  22. * @access public
  23. * @param string $image 图像文件名
  24. * @return mixed
  25. */
  26. static function getImageInfo($img) {
  27. $imageInfo = getimagesize($img);
  28. if ($imageInfo !== false) {
  29. $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
  30. $imageSize = filesize($img);
  31. $info = array(
  32. "width" => $imageInfo[0],
  33. "height" => $imageInfo[1],
  34. "type" => $imageType,
  35. "size" => $imageSize,
  36. "mime" => $imageInfo['mime']
  37. );
  38. return $info;
  39. } else {
  40. return false;
  41. }
  42. }
  43. /**
  44. * 为图片添加水印
  45. * @static public
  46. * @param string $source 原文件名
  47. * @param string $water 水印图片
  48. * @param string $$savename 添加水印后的图片名
  49. * @param string $alpha 水印的透明度
  50. * @return void
  51. */
  52. static public function water($source, $water, $savename=null, $alpha=80) {
  53. //检查文件是否存在
  54. if (!file_exists($source) || !file_exists($water))
  55. return false;
  56. //图片信息
  57. $sInfo = self::getImageInfo($source);
  58. $wInfo = self::getImageInfo($water);
  59. //如果图片小于水印图片,不生成图片
  60. if ($sInfo["width"] < $wInfo["width"] || $sInfo['height'] < $wInfo['height'])
  61. return false;
  62. //建立图像
  63. $sCreateFun = "imagecreatefrom" . $sInfo['type'];
  64. $sImage = $sCreateFun($source);
  65. $wCreateFun = "imagecreatefrom" . $wInfo['type'];
  66. $wImage = $wCreateFun($water);
  67. //设定图像的混色模式
  68. imagealphablending($wImage, true);
  69. //图像位置,默认为右下角右对齐
  70. $posY = $sInfo["height"] - $wInfo["height"];
  71. $posX = $sInfo["width"] - $wInfo["width"];
  72. //生成混合图像
  73. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo['width'], $wInfo['height'], $alpha);
  74. //输出图像
  75. $ImageFun = 'Image' . $sInfo['type'];
  76. //如果没有给出保存文件名,默认为原图像名
  77. if (!$savename) {
  78. $savename = $source;
  79. @unlink($source);
  80. }
  81. //保存图像
  82. $ImageFun($sImage, $savename);
  83. imagedestroy($sImage);
  84. }
  85. function showImg($imgFile, $text='', $x='10', $y='10', $alpha='50') {
  86. //获取图像文件信息
  87. //2007/6/26 增加图片水印输出,$text为图片的完整路径即可
  88. $info = Image::getImageInfo($imgFile);
  89. if ($info !== false) {
  90. $createFun = str_replace('/', 'createfrom', $info['mime']);
  91. $im = $createFun($imgFile);
  92. if ($im) {
  93. $ImageFun = str_replace('/', '', $info['mime']);
  94. //水印开始
  95. if (!empty($text)) {
  96. $tc = imagecolorallocate($im, 0, 0, 0);
  97. if (is_file($text) && file_exists($text)) {//判断$text是否是图片路径
  98. // 取得水印信息
  99. $textInfo = Image::getImageInfo($text);
  100. $createFun2 = str_replace('/', 'createfrom', $textInfo['mime']);
  101. $waterMark = $createFun2($text);
  102. //$waterMark=imagecolorallocatealpha($text,255,255,0,50);
  103. $imgW = $info["width"];
  104. $imgH = $info["width"] * $textInfo["height"] / $textInfo["width"];
  105. //$y = ($info["height"]-$textInfo["height"])/2;
  106. //设置水印的显示位置和透明度支持各种图片格式
  107. imagecopymerge($im, $waterMark, $x, $y, 0, 0, $textInfo['width'], $textInfo['height'], $alpha);
  108. } else {
  109. imagestring($im, 80, $x, $y, $text, $tc);
  110. }
  111. //ImageDestroy($tc);
  112. }
  113. //水印结束
  114. if ($info['type'] == 'png' || $info['type'] == 'gif') {
  115. imagealphablending($im, FALSE); //取消默认的混色模式
  116. imagesavealpha($im, TRUE); //设定保存完整的 alpha 通道信息
  117. }
  118. Header("Content-type: " . $info['mime']);
  119. $ImageFun($im);
  120. @ImageDestroy($im);
  121. return;
  122. }
  123. //保存图像
  124. $ImageFun($sImage, $savename);
  125. imagedestroy($sImage);
  126. //获取或者创建图像文件失败则生成空白PNG图片
  127. $im = imagecreatetruecolor(80, 30);
  128. $bgc = imagecolorallocate($im, 255, 255, 255);
  129. $tc = imagecolorallocate($im, 0, 0, 0);
  130. imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
  131. imagestring($im, 4, 5, 5, "no pic", $tc);
  132. Image::output($im);
  133. return;
  134. }
  135. }
  136. /**
  137. * 生成缩略图
  138. * @static
  139. * @access public
  140. * @param string $image 原图
  141. * @param string $type 图像格式
  142. * @param string $thumbname 缩略图文件名
  143. * @param string $maxWidth 宽度
  144. * @param string $maxHeight 高度
  145. * @param string $position 缩略图保存目录
  146. * @param boolean $interlace 启用隔行扫描
  147. * @return void
  148. */
  149. static function thumb($image, $thumbname, $type='', $maxWidth=200, $maxHeight=50, $interlace=true) {
  150. // 获取原图信息
  151. $info = Image::getImageInfo($image);
  152. if ($info !== false) {
  153. $srcWidth = $info['width'];
  154. $srcHeight = $info['height'];
  155. $type = empty($type) ? $info['type'] : $type;
  156. $type = strtolower($type);
  157. $interlace = $interlace ? 1 : 0;
  158. unset($info);
  159. $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 计算缩放比例
  160. if ($scale >= 1) {
  161. // 超过原图大小不再缩略
  162. $width = $srcWidth;
  163. $height = $srcHeight;
  164. } else {
  165. // 缩略图尺寸
  166. $width = (int) ($srcWidth * $scale);
  167. $height = (int) ($srcHeight * $scale);
  168. }
  169. // 载入原图
  170. $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
  171. if(!function_exists($createFun)) {
  172. return false;
  173. }
  174. $srcImg = $createFun($image);
  175. //创建缩略图
  176. if ($type != 'gif' && function_exists('imagecreatetruecolor'))
  177. $thumbImg = imagecreatetruecolor($width, $height);
  178. else
  179. $thumbImg = imagecreate($width, $height);
  180. //png和gif的透明处理 by luofei614
  181. if('png'==$type){
  182. imagealphablending($thumbImg, false);//取消默认的混色模式(为解决阴影为绿色的问题)
  183. imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息(为解决阴影为绿色的问题)
  184. }elseif('gif'==$type){
  185. $trnprt_indx = imagecolortransparent($srcImg);
  186. if ($trnprt_indx >= 0) {
  187. //its transparent
  188. $trnprt_color = imagecolorsforindex($srcImg , $trnprt_indx);
  189. $trnprt_indx = imagecolorallocate($thumbImg, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
  190. imagefill($thumbImg, 0, 0, $trnprt_indx);
  191. imagecolortransparent($thumbImg, $trnprt_indx);
  192. }
  193. }
  194. // 复制图片
  195. if (function_exists("ImageCopyResampled"))
  196. imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
  197. else
  198. imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
  199. // 对jpeg图形设置隔行扫描
  200. if ('jpg' == $type || 'jpeg' == $type)
  201. imageinterlace($thumbImg, $interlace);
  202. // 生成图片
  203. $imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type);
  204. $imageFun($thumbImg, $thumbname);
  205. imagedestroy($thumbImg);
  206. imagedestroy($srcImg);
  207. return $thumbname;
  208. }
  209. return false;
  210. }
  211. /**
  212. * 根据给定的字符串生成图像
  213. * @static
  214. * @access public
  215. * @param string $string 字符串
  216. * @param string $size 图像大小 width,height 或者 array(width,height)
  217. * @param string $font 字体信息 fontface,fontsize 或者 array(fontface,fontsize)
  218. * @param string $type 图像格式 默认PNG
  219. * @param integer $disturb 是否干扰 1 点干扰 2 线干扰 3 复合干扰 0 无干扰
  220. * @param bool $border 是否加边框 array(color)
  221. * @return string
  222. */
  223. static function buildString($string, $rgb=array(), $filename='', $type='png', $disturb=1, $border=true) {
  224. if (is_string($size))
  225. $size = explode(',', $size);
  226. $width = $size[0];
  227. $height = $size[1];
  228. if (is_string($font))
  229. $font = explode(',', $font);
  230. $fontface = $font[0];
  231. $fontsize = $font[1];
  232. $length = strlen($string);
  233. $width = ($length * 9 + 10) > $width ? $length * 9 + 10 : $width;
  234. $height = 22;
  235. if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
  236. $im = @imagecreatetruecolor($width, $height);
  237. } else {
  238. $im = @imagecreate($width, $height);
  239. }
  240. if (empty($rgb)) {
  241. $color = imagecolorallocate($im, 102, 104, 104);
  242. } else {
  243. $color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);
  244. }
  245. $backColor = imagecolorallocate($im, 255, 255, 255); //背景色(随机)
  246. $borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
  247. $pointColor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); //点颜色
  248. @imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
  249. @imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
  250. @imagestring($im, 5, 5, 3, $string, $color);
  251. if (!empty($disturb)) {
  252. // 添加干扰
  253. if ($disturb = 1 || $disturb = 3) {
  254. for ($i = 0; $i < 25; $i++) {
  255. imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pointColor);
  256. }
  257. } elseif ($disturb = 2 || $disturb = 3) {
  258. for ($i = 0; $i < 10; $i++) {
  259. imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $pointColor);
  260. }
  261. }
  262. }
  263. Image::output($im, $type, $filename);
  264. }
  265. /**
  266. * 生成图像验证码
  267. * @static
  268. * @access public
  269. * @param string $length 位数
  270. * @param string $mode 类型
  271. * @param string $type 图像格式
  272. * @param string $width 宽度
  273. * @param string $height 高度
  274. * @return string
  275. */
  276. static function buildImageVerify($length=4, $mode=1, $type='png', $width=48, $height=22, $verifyName='verify') {
  277. import('ORG.Util.String');
  278. $randval = String::randString($length, $mode);
  279. session($verifyName, md5($randval));
  280. $width = ($length * 10 + 10) > $width ? $length * 10 + 10 : $width;
  281. if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
  282. $im = imagecreatetruecolor($width, $height);
  283. } else {
  284. $im = imagecreate($width, $height);
  285. }
  286. $r = Array(225, 255, 255, 223);
  287. $g = Array(225, 236, 237, 255);
  288. $b = Array(225, 236, 166, 125);
  289. $key = mt_rand(0, 3);
  290. $backColor = imagecolorallocate($im, $r[$key], $g[$key], $b[$key]); //背景色(随机)
  291. $borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
  292. imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
  293. imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
  294. $stringColor = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
  295. // 干扰
  296. for ($i = 0; $i < 10; $i++) {
  297. imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $stringColor);
  298. }
  299. for ($i = 0; $i < 25; $i++) {
  300. imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $stringColor);
  301. }
  302. for ($i = 0; $i < $length; $i++) {
  303. imagestring($im, 5, $i * 10 + 5, mt_rand(1, 8), $randval{$i}, $stringColor);
  304. }
  305. Image::output($im, $type);
  306. }
  307. // 中文验证码
  308. static function GBVerify($length=4, $type='png', $width=180, $height=50, $fontface='simhei.ttf', $verifyName='verify') {
  309. import('ORG.Util.String');
  310. $code = String::randString($length, 4);
  311. $width = ($length * 45) > $width ? $length * 45 : $width;
  312. session($verifyName, md5($code));
  313. $im = imagecreatetruecolor($width, $height);
  314. $borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
  315. $bkcolor = imagecolorallocate($im, 250, 250, 250);
  316. imagefill($im, 0, 0, $bkcolor);
  317. @imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
  318. // 干扰
  319. for ($i = 0; $i < 15; $i++) {
  320. $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
  321. imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor);
  322. }
  323. for ($i = 0; $i < 255; $i++) {
  324. $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
  325. imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $fontcolor);
  326. }
  327. if (!is_file($fontface)) {
  328. $fontface = dirname(__FILE__) . "/" . $fontface;
  329. }
  330. for ($i = 0; $i < $length; $i++) {
  331. $fontcolor = imagecolorallocate($im, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)); //这样保证随机出来的颜色较深。
  332. $codex = String::msubstr($code, $i, 1);
  333. imagettftext($im, mt_rand(16, 20), mt_rand(-60, 60), 40 * $i + 20, mt_rand(30, 35), $fontcolor, $fontface, $codex);
  334. }
  335. Image::output($im, $type);
  336. }
  337. /**
  338. * 把图像转换成字符显示
  339. * @static
  340. * @access public
  341. * @param string $image 要显示的图像
  342. * @param string $type 图像类型,默认自动获取
  343. * @return string
  344. */
  345. static function showASCIIImg($image, $string='', $type='') {
  346. $info = Image::getImageInfo($image);
  347. if ($info !== false) {
  348. $type = empty($type) ? $info['type'] : $type;
  349. unset($info);
  350. // 载入原图
  351. $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
  352. $im = $createFun($image);
  353. $dx = imagesx($im);
  354. $dy = imagesy($im);
  355. $i = 0;
  356. $out = '<span style="padding:0px;margin:0;line-height:100%;font-size:1px;">';
  357. set_time_limit(0);
  358. for ($y = 0; $y < $dy; $y++) {
  359. for ($x = 0; $x < $dx; $x++) {
  360. $col = imagecolorat($im, $x, $y);
  361. $rgb = imagecolorsforindex($im, $col);
  362. $str = empty($string) ? '*' : $string[$i++];
  363. $out .= sprintf('<span style="margin:0px;color:#%02x%02x%02x">' . $str . '</span>', $rgb['red'], $rgb['green'], $rgb['blue']);
  364. }
  365. $out .= "<br>\n";
  366. }
  367. $out .= '</span>';
  368. imagedestroy($im);
  369. return $out;
  370. }
  371. return false;
  372. }
  373. /**
  374. * 生成UPC-A条形码
  375. * @static
  376. * @param string $type 图像格式
  377. * @param string $type 图像格式
  378. * @param string $lw 单元宽度
  379. * @param string $hi 条码高度
  380. * @return string
  381. */
  382. static function UPCA($code, $type='png', $lw=2, $hi=100) {
  383. static $Lencode = array('0001101', '0011001', '0010011', '0111101', '0100011',
  384. '0110001', '0101111', '0111011', '0110111', '0001011');
  385. static $Rencode = array('1110010', '1100110', '1101100', '1000010', '1011100',
  386. '1001110', '1010000', '1000100', '1001000', '1110100');
  387. $ends = '101';
  388. $center = '01010';
  389. /* UPC-A Must be 11 digits, we compute the checksum. */
  390. if (strlen($code) != 11) {
  391. die("UPC-A Must be 11 digits.");
  392. }
  393. /* Compute the EAN-13 Checksum digit */
  394. $ncode = '0' . $code;
  395. $even = 0;
  396. $odd = 0;
  397. for ($x = 0; $x < 12; $x++) {
  398. if ($x % 2) {
  399. $odd += $ncode[$x];
  400. } else {
  401. $even += $ncode[$x];
  402. }
  403. }
  404. $code.= ( 10 - (($odd * 3 + $even) % 10)) % 10;
  405. /* Create the bar encoding using a binary string */
  406. $bars = $ends;
  407. $bars.=$Lencode[$code[0]];
  408. for ($x = 1; $x < 6; $x++) {
  409. $bars.=$Lencode[$code[$x]];
  410. }
  411. $bars.=$center;
  412. for ($x = 6; $x < 12; $x++) {
  413. $bars.=$Rencode[$code[$x]];
  414. }
  415. $bars.=$ends;
  416. /* Generate the Barcode Image */
  417. if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
  418. $im = imagecreatetruecolor($lw * 95 + 30, $hi + 30);
  419. } else {
  420. $im = imagecreate($lw * 95 + 30, $hi + 30);
  421. }
  422. $fg = ImageColorAllocate($im, 0, 0, 0);
  423. $bg = ImageColorAllocate($im, 255, 255, 255);
  424. ImageFilledRectangle($im, 0, 0, $lw * 95 + 30, $hi + 30, $bg);
  425. $shift = 10;
  426. for ($x = 0; $x < strlen($bars); $x++) {
  427. if (($x < 10) || ($x >= 45 && $x < 50) || ($x >= 85)) {
  428. $sh = 10;
  429. } else {
  430. $sh = 0;
  431. }
  432. if ($bars[$x] == '1') {
  433. $color = $fg;
  434. } else {
  435. $color = $bg;
  436. }
  437. ImageFilledRectangle($im, ($x * $lw) + 15, 5, ($x + 1) * $lw + 14, $hi + 5 + $sh, $color);
  438. }
  439. /* Add the Human Readable Label */
  440. ImageString($im, 4, 5, $hi - 5, $code[0], $fg);
  441. for ($x = 0; $x < 5; $x++) {
  442. ImageString($im, 5, $lw * (13 + $x * 6) + 15, $hi + 5, $code[$x + 1], $fg);
  443. ImageString($im, 5, $lw * (53 + $x * 6) + 15, $hi + 5, $code[$x + 6], $fg);
  444. }
  445. ImageString($im, 4, $lw * 95 + 17, $hi - 5, $code[11], $fg);
  446. /* Output the Header and Content. */
  447. Image::output($im, $type);
  448. }
  449. static function output($im, $type='png', $filename='') {
  450. header("Content-type: image/" . $type);
  451. $ImageFun = 'image' . $type;
  452. if (empty($filename)) {
  453. $ImageFun($im);
  454. } else {
  455. $ImageFun($im, $filename);
  456. }
  457. imagedestroy($im);
  458. }
  459. }