PageRenderTime 54ms CodeModel.GetById 2ms app.highlight 43ms RepoModel.GetById 1ms app.codeStats 0ms

/addons/library/Image.class.php

https://github.com/cxc222/weibo
PHP | 858 lines | 567 code | 66 blank | 225 comment | 114 complexity | fc7ef1ae7b7cf1e9f6472e1021a3910d 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// $Id$
 12
 13/**
 14 +------------------------------------------------------------------------------
 15 * 图像操作类库
 16 +------------------------------------------------------------------------------
 17 * @category   ORG
 18 * @package  ORG
 19 * @subpackage  Util
 20 * @author    liu21st <liu21st@gmail.com>
 21 * @version   $Id$
 22 +------------------------------------------------------------------------------
 23 */
 24class Image
 25{//类定义开始
 26
 27    /**
 28     +----------------------------------------------------------
 29     * 取得图像信息
 30     *
 31     +----------------------------------------------------------
 32     * @static
 33     * @access public
 34     +----------------------------------------------------------
 35     * @param string $image 图像文件名
 36     +----------------------------------------------------------
 37     * @return mixed
 38     +----------------------------------------------------------
 39     */
 40    static function getImageInfo($img) {
 41        $imageInfo = getimagesize($img);
 42        if( $imageInfo!== false) {
 43            $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]),1));
 44            $imageSize = filesize($img);
 45            $info = array(
 46                "width"=>$imageInfo[0],
 47                "height"=>$imageInfo[1],
 48                "type"=>$imageType,
 49                "size"=>$imageSize,
 50                "mime"=>$imageInfo['mime']
 51            );
 52            return $info;
 53        }else {
 54            return false;
 55        }
 56    }
 57
 58    /**
 59     +----------------------------------------------------------
 60     * 显示服务器图像文件
 61     * 支持URL方式
 62     +----------------------------------------------------------
 63     * @static
 64     * @access public
 65     +----------------------------------------------------------
 66     * @param string $imgFile 图像文件名
 67     * @param string $text 文字字符串
 68     * @param string $width 图像宽度
 69     * @param string $height 图像高度
 70     +----------------------------------------------------------
 71     * @return void
 72     +----------------------------------------------------------
 73     */
 74    static function showImg($imgFile,$text='',$width=80,$height=30) {
 75        //获取图像文件信息
 76        $info = Image::getImageInfo($imgFile);
 77        if($info !== false) {
 78            $createFun  =   str_replace('/','createfrom',$info['mime']);
 79            $im = $createFun($imgFile);
 80            if($im) {
 81                $ImageFun= str_replace('/','',$info['mime']);
 82                if(!empty($text)) {
 83                    $tc  = imagecolorallocate($im, 0, 0, 0);
 84                    imagestring($im, 3, 5, 5, $text, $tc);
 85                }
 86                if($info['type']=='png' || $info['type']=='gif') {
 87                imagealphablending($im, false);//取消默认的混色模式
 88                imagesavealpha($im,true);//设定保存完整的 alpha 通道信息
 89                }
 90                header("Content-type: ".$info['mime']);
 91                $ImageFun($im);
 92                imagedestroy($im);
 93                return ;
 94            }
 95        }
 96        //获取或者创建图像文件失败则生成空白PNG图片
 97        $im  = imagecreatetruecolor($width, $height);
 98        $bgc = imagecolorallocate($im, 255, 255, 255);
 99        $tc  = imagecolorallocate($im, 0, 0, 0);
100        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
101        imagestring($im, 4, 5, 5, "NO PIC", $tc);
102        Image::output($im);
103        return ;
104    }
105
106    /**
107     * 切割图片
108     +----------------------------------------------------------
109     * @static
110     * @access public
111     +----------------------------------------------------------
112     * @param string $image  原图
113     * @param string $cutfile 切割后的图片
114     * @param int $cutWidth
115     * @param int $cutHeight
116     +----------------------------------------------------------
117     * @return void
118     */
119    static function cut($image,$filename,$maxWidth='',$maxHeight=''){
120
121        // 获取原图信息
122        $info  = Image::getImageInfo($image);
123        //dump($image);
124        if($info !== false) {
125            $srcWidth  = $info['width'];
126            $srcHeight = $info['height'];
127            $pathinfo = pathinfo($image);
128            $type =  $pathinfo['extension'];
129            $type = empty($type)?$info['type']:$type;
130            $type   =   strtolower($type);
131            $interlace  =  $interlace? 1:0;
132            unset($info);
133            // 载入原图
134            $createFun = 'ImageCreateFrom'.($type=='jpg'?'jpeg':$type);
135            $srcImg     = $createFun($image);
136
137            //创建缩略图
138            if($type!='gif' && function_exists('imagecreatetruecolor'))
139                $thumbImg = imagecreatetruecolor($maxWidth, $maxHeight);
140            else
141                $thumbImg = imagecreate($maxWidth, $maxHeight);
142
143            // 新建PNG缩略图通道透明处理
144            if('png'==$type) {
145                imagealphablending($thumbImg, false);//取消默认的混色模式
146                imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息
147            }elseif('gif'==$type) {
148            // 新建GIF缩略图预处理,保证透明效果不失效
149                $background_color  =  imagecolorallocate($thumbImg,  0,255,0);  //  指派一个绿色
150                imagecolortransparent($thumbImg,$background_color);  //  设置为透明色,若注释掉该行则输出绿色的图
151            }
152
153            // 计算缩放比例
154            if(($maxWidth/$maxHeight)>=($srcWidth/$srcHeight)){
155                //宽不变,截高,从中间截取 y=
156                $width  =   $srcWidth;
157                $height =   $srcWidth*($maxHeight/$maxWidth);
158                $x      =   0;
159                $y      =   ($srcHeight-$height)*0.5;
160            }else{
161                //高不变,截宽,从中间截取,x=
162                $width  =   $srcHeight*($maxWidth/$maxHeight);
163                $height =   $srcHeight;
164                $x      =   ($srcWidth-$width)*0.5;
165                $y      =   0;
166            }
167            // 复制图片
168            if(function_exists("ImageCopyResampled")){
169                ImageCopyResampled($thumbImg, $srcImg, 0, 0, $x, $y, $maxWidth, $maxHeight, $width,$height);
170            }else{
171                ImageCopyResized($thumbImg, $srcImg, 0, 0, $x, $y, $maxWidth, $maxHeight,  $width,$height);
172            }
173            ImageDestroy($srcImg);
174
175            // 对jpeg图形设置隔行扫描
176            if('jpg'==$type || 'jpeg'==$type)   imageinterlace($thumbImg,$interlace);
177
178            // 生成图片
179            //$imageFun = 'image'.($type=='jpg'?'jpeg':$type);
180            $imageFun   =   'imagepng';
181            $filename  = empty($filename)? substr($image,0,strrpos($image, '.')).$suffix.'.'.$type : $filename;
182
183            $imageFun($thumbImg,$filename);
184            ImageDestroy($thumbImg);
185            return $filename;
186         }
187         return false;
188    }
189    /**
190
191     +----------------------------------------------------------
192     * 生成缩略图
193     +----------------------------------------------------------
194     * @static
195     * @access public
196     +----------------------------------------------------------
197     * @param string $image  原图
198     * @param string $type 图像格式
199     * @param string $thumbname 缩略图文件名
200     * @param string $maxWidth  宽度
201     * @param string $maxHeight  高度
202     * @param string $position 缩略图保存目录
203     * @param boolean $interlace 启用隔行扫描
204     +----------------------------------------------------------
205     * @return void
206     +----------------------------------------------------------
207     */
208    static function thumb($image,$thumbname,$type='',$maxWidth=200,$maxHeight='auto',$interlace=true)
209    {
210        // 获取原图信息
211        $info  = Image::getImageInfo($image);
212         if($info !== false) {
213            $srcWidth  = $info['width'];
214            $srcHeight = $info['height'];
215            $type = empty($type)?$info['type']:$type;
216			$type = strtolower($type);
217            $interlace  =  $interlace? 1:0;
218            unset($info);
219            if( $maxHeight=='auto' ){
220           		$scale = $maxWidth/$srcWidth;
221            }else{
222            	$scale = min($maxWidth/$srcWidth, $maxHeight/$srcHeight); // 计算缩放比例
223            }
224            if($scale>=1) {
225                // 超过原图大小不再缩略
226                $width   =  $srcWidth;
227                $height  =  $srcHeight;
228            }else{
229                // 缩略图尺寸
230                $width  = (int)($srcWidth*$scale);
231                $height = (int)($srcHeight*$scale);
232            }
233
234            // 载入原图
235            $createFun = 'ImageCreateFrom'.($type=='jpg'?'jpeg':$type);
236            $srcImg     = $createFun($image);
237
238            //创建缩略图
239            if($type!='gif' && function_exists('imagecreatetruecolor'))
240                $thumbImg = imagecreatetruecolor($width, $height);
241            else
242                $thumbImg = imagecreate($width, $height);
243
244            // 新建PNG缩略图通道透明处理
245            if('png'==$type) {
246                imagealphablending($thumbImg, false);//取消默认的混色模式
247                imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息
248            }elseif('gif'==$type) {
249            // 新建GIF缩略图预处理,保证透明效果不失效
250	            $background_color  =  imagecolorallocate($thumbImg,  0,255,0);  //  指派一个绿色
251	            imagecolortransparent($thumbImg,$background_color);  //  设置为透明色,若注释掉该行则输出绿色的图
252            }
253
254            // 复制图片
255            if(function_exists("ImageCopyResampled"))
256                imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth,$srcHeight);
257            else
258                imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height,  $srcWidth,$srcHeight);
259            /*if('gif'==$type || 'png'==$type) {
260                //imagealphablending($thumbImg, false);//取消默认的混色模式
261                //imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息
262                $background_color  =  imagecolorallocate($thumbImg,  0,255,0);  //  指派一个绿色
263				imagecolortransparent($thumbImg,$background_color);  //  设置为透明色,若注释掉该行则输出绿色的图
264            }*/
265
266            // 对jpeg图形设置隔行扫描
267            if('jpg'==$type || 'jpeg'==$type) 	imageinterlace($thumbImg,$interlace);
268
269            //$gray=ImageColorAllocate($thumbImg,255,0,0);
270            //ImageString($thumbImg,2,5,5,"ThinkPHP",$gray);
271            // 生成图片
272            $imageFun = 'image'.($type=='jpg'?'jpeg':$type);
273            $imageFun($thumbImg,$thumbname);
274            imagedestroy($thumbImg);
275            imagedestroy($srcImg);
276            return $thumbname;
277         }
278         return false;
279    }
280
281    /**
282     +----------------------------------------------------------
283     * 根据给定的字符串生成图像
284     +----------------------------------------------------------
285     * @static
286     * @access public
287     +----------------------------------------------------------
288     * @param string $string  字符串
289     * @param string $size  图像大小 width,height 或者 array(width,height)
290     * @param string $font  字体信息 fontface,fontsize 或者 array(fontface,fontsize)
291     * @param string $type 图像格式 默认PNG
292     * @param integer $disturb 是否干扰 1 点干扰 2 线干扰 3 复合干扰 0 无干扰
293	 * @param bool $border  是否加边框 array(color)
294     +----------------------------------------------------------
295     * @return string
296     +----------------------------------------------------------
297     */
298	static function buildString($string,$rgb=array(),$filename='',$type='png',$disturb=1,$border=true) {
299		if(is_string($size))		$size	=	explode(',',$size);
300		$width	=	$size[0];
301		$height	=	$size[1];
302		if(is_string($font))		$font	=	explode(',',$font);
303		$fontface	=	$font[0];
304		$fontsize	 	=	$font[1];
305		$length		=	strlen($string);
306        $width = ($length*9+10)>$width?$length*9+10:$width;
307		$height	=	22;
308        if ( $type!='gif' && function_exists('imagecreatetruecolor')) {
309            $im = @imagecreatetruecolor($width,$height);
310        }else {
311            $im = @imagecreate($width,$height);
312        }
313		if(empty($rgb)) {
314			$color = imagecolorallocate($im, 102, 104, 104);
315		}else{
316			$color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);
317		}
318        $backColor = imagecolorallocate($im, 255,255,255);    //背景色(随机)
319		$borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色
320        $pointColor = imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));                 //点颜色
321
322        @imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
323        @imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
324        @imagestring($im, 5, 5, 3, $string, $color);
325		if(!empty($disturb)) {
326			// 添加干扰
327			if($disturb=1 || $disturb=3) {
328				for($i=0;$i<25;$i++){
329					imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pointColor);
330				}
331			}elseif($disturb=2 || $disturb=3){
332				for($i=0;$i<10;$i++){
333					imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$pointColor);
334				}
335			}
336		}
337        Image::output($im,$type,$filename);
338	}
339
340    /**
341     +----------------------------------------------------------
342     * 生成图像验证码
343     +----------------------------------------------------------
344     * @static
345     * @access public
346     +----------------------------------------------------------
347     * @param string $length  位数
348     * @param string $mode  类型
349     * @param string $type 图像格式
350     * @param string $width  宽度
351     * @param string $height  高度
352     +----------------------------------------------------------
353     * @return string
354     +----------------------------------------------------------
355     */
356    static function buildImageVerify($length=4,$mode=1,$type='png',$width=48,$height=22,$verifyName='verify')
357    {
358		tsload(ADDON_PATH.'/library/String.class.php');
359        $randval = String::rand_string($length,$mode);
360        //转换成大写字母.
361        $_SESSION[$verifyName]= md5(strtoupper($randval));
362        $width = ($length*10+10)>$width?$length*10+10:$width;
363        if ( $type!='gif' && function_exists('imagecreatetruecolor')) {
364            $im = @imagecreatetruecolor($width,$height);
365        }else {
366            $im = @imagecreate($width,$height);
367        }
368        $r = Array(225,255,255,223);
369        $g = Array(225,236,237,255);
370        $b = Array(225,236,166,125);
371        $key = mt_rand(0,3);
372
373        $backColor = imagecolorallocate($im, $r[$key],$g[$key],$b[$key]);    //背景色(随机)
374		$borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色
375        $pointColor = imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));                 //点颜色
376
377        @imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
378        @imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
379        $stringColor = imagecolorallocate($im,mt_rand(0,200),mt_rand(0,120),mt_rand(0,120));
380		// 干扰
381		for($i=0;$i<10;$i++){
382			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
383			imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$fontcolor);
384		}
385		for($i=0;$i<25;$i++){
386			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
387			imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pointColor);
388		}
389		for($i=0;$i<$length;$i++) {
390			imagestring($im,5,$i*10+5,mt_rand(1,8),$randval{$i}, $stringColor);
391		}
392//        @imagestring($im, 5, 5, 3, $randval, $stringColor);
393        Image::output($im,$type);
394    }
395
396	// 中文验证码
397	static function GBVerify($length=4,$type='png',$width=180,$height=50,$fontface='simhei.ttf',$verifyName='verify') {
398		tsload(ADDON_PATH.'/library/String.class.php');
399        $code = String::rand_string($length,4);
400        $width = ($length*45)>$width?$length*45:$width;
401		$_SESSION[$verifyName]= md5($code);
402		$im=imagecreatetruecolor($width,$height);
403		$borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色
404		$bkcolor=imagecolorallocate($im,250,250,250);
405		imagefill($im,0,0,$bkcolor);
406        @imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
407		// 干扰
408		for($i=0;$i<15;$i++){
409			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
410			imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$fontcolor);
411		}
412		for($i=0;$i<255;$i++){
413			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
414			imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$fontcolor);
415		}
416		if(!is_file($fontface)) {
417			$fontface = dirname(__FILE__)."/".$fontface;
418		}
419		for($i=0;$i<$length;$i++){
420			$fontcolor=imagecolorallocate($im,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120)); //这样保证随机出来的颜色较深。
421			$codex= String::msubstr($code,$i,1);
422			imagettftext($im,mt_rand(16,20),mt_rand(-60,60),40*$i+20,mt_rand(30,35),$fontcolor,$fontface,$codex);
423		}
424		Image::output($im,$type);
425	}
426
427    /**
428     +----------------------------------------------------------
429     * 把图像转换成字符显示
430     +----------------------------------------------------------
431     * @static
432     * @access public
433     +----------------------------------------------------------
434     * @param string $image  要显示的图像
435     * @param string $type  图像类型,默认自动获取
436     +----------------------------------------------------------
437     * @return string
438     +----------------------------------------------------------
439     */
440    static function showASCIIImg($image,$string='',$type='')
441    {
442        $info  = Image::getImageInfo($image);
443        if($info !== false) {
444            $type = empty($type)?$info['type']:$type;
445            unset($info);
446            // 载入原图
447            $createFun = 'ImageCreateFrom'.($type=='jpg'?'jpeg':$type);
448            $im     = $createFun($image);
449            $dx = imagesx($im);
450            $dy = imagesy($im);
451			$i	=	0;
452            $out   =  '<span style="padding:0px;margin:0;line-height:100%;font-size:1px;">';
453			set_time_limit(0);
454            for($y = 0; $y < $dy; $y++) {
455              for($x=0; $x < $dx; $x++) {
456                  $col = imagecolorat($im, $x, $y);
457                  $rgb = imagecolorsforindex($im,$col);
458				  $str	 =	 empty($string)?'*':$string[$i++];
459                  $out .= sprintf('<span style="margin:0px;color:#%02x%02x%02x">'.$str.'</span>',$rgb['red'],$rgb['green'],$rgb['blue']);
460             }
461             $out .= "<br>\n";
462            }
463            $out .=  '</span>';
464            imagedestroy($im);
465            return $out;
466        }
467        return false;
468    }
469
470    /**
471     +----------------------------------------------------------
472     * 生成高级图像验证码
473     +----------------------------------------------------------
474     * @static
475     * @access public
476     +----------------------------------------------------------
477     * @param string $type 图像格式
478     * @param string $width  宽度
479     * @param string $height  高度
480     +----------------------------------------------------------
481     * @return string
482     +----------------------------------------------------------
483     */
484    static function showAdvVerify($type='png',$width=180,$height=40,$verifyName='verifyCode')
485    {
486		$rand	=	range('a','z');
487		shuffle($rand);
488		$verifyCode	=	array_slice($rand,0,10);
489        $letter = implode(" ",$verifyCode);
490        $_SESSION[$verifyName] = $verifyCode;
491        $im = imagecreate($width,$height);
492        $r = array(225,255,255,223);
493        $g = array(225,236,237,255);
494        $b = array(225,236,166,125);
495        $key = mt_rand(0,3);
496        $backColor = imagecolorallocate($im, $r[$key],$g[$key],$b[$key]);
497		$borderColor = imagecolorallocate($im, 100, 100, 100);                    //边框色
498        imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
499        imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
500        $numberColor = imagecolorallocate($im, 255,rand(0,100), rand(0,100));
501        $stringColor = imagecolorallocate($im, rand(0,100), rand(0,100), 255);
502		// 添加干扰
503		/*
504		for($i=0;$i<10;$i++){
505			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
506			imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$fontcolor);
507		}
508		for($i=0;$i<255;$i++){
509			$fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
510			imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$fontcolor);
511		}*/
512        imagestring($im, 5, 5, 1, "0 1 2 3 4 5 6 7 8 9", $numberColor);
513        imagestring($im, 5, 5, 20, $letter, $stringColor);
514        Image::output($im,$type);
515    }
516
517    /**
518     +----------------------------------------------------------
519     * 生成UPC-A条形码
520     +----------------------------------------------------------
521     * @static
522     +----------------------------------------------------------
523     * @param string $type 图像格式
524     * @param string $type 图像格式
525     * @param string $lw  单元宽度
526     * @param string $hi   条码高度
527     +----------------------------------------------------------
528     * @return string
529     +----------------------------------------------------------
530     */
531    static function UPCA($code,$type='png',$lw=2,$hi=100) {
532        static $Lencode = array('0001101','0011001','0010011','0111101','0100011',
533                         '0110001','0101111','0111011','0110111','0001011');
534        static $Rencode = array('1110010','1100110','1101100','1000010','1011100',
535                         '1001110','1010000','1000100','1001000','1110100');
536        $ends = '101';
537        $center = '01010';
538        /* UPC-A Must be 11 digits, we compute the checksum. */
539        if ( strlen($code) != 11 ) { die("UPC-A Must be 11 digits."); }
540        /* Compute the EAN-13 Checksum digit */
541        $ncode = '0'.$code;
542        $even = 0; $odd = 0;
543        for ($x=0;$x<12;$x++) {
544          if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; }
545        }
546        $code.=(10 - (($odd * 3 + $even) % 10)) % 10;
547        /* Create the bar encoding using a binary string */
548        $bars=$ends;
549        $bars.=$Lencode[$code[0]];
550        for($x=1;$x<6;$x++) {
551          $bars.=$Lencode[$code[$x]];
552        }
553        $bars.=$center;
554        for($x=6;$x<12;$x++) {
555          $bars.=$Rencode[$code[$x]];
556        }
557        $bars.=$ends;
558        /* Generate the Barcode Image */
559        if ( $type!='gif' && function_exists('imagecreatetruecolor')) {
560            $im = imagecreatetruecolor($lw*95+30,$hi+30);
561        }else {
562            $im = imagecreate($lw*95+30,$hi+30);
563        }
564        $fg = ImageColorAllocate($im, 0, 0, 0);
565        $bg = ImageColorAllocate($im, 255, 255, 255);
566        ImageFilledRectangle($im, 0, 0, $lw*95+30, $hi+30, $bg);
567        $shift=10;
568        for ($x=0;$x<strlen($bars);$x++) {
569          if (($x<10) || ($x>=45 && $x<50) || ($x >=85)) { $sh=10; } else { $sh=0; }
570          if ($bars[$x] == '1') { $color = $fg; } else { $color = $bg; }
571          ImageFilledRectangle($im, ($x*$lw)+15,5,($x+1)*$lw+14,$hi+5+$sh,$color);
572        }
573        /* Add the Human Readable Label */
574        ImageString($im,4,5,$hi-5,$code[0],$fg);
575        for ($x=0;$x<5;$x++) {
576          ImageString($im,5,$lw*(13+$x*6)+15,$hi+5,$code[$x+1],$fg);
577          ImageString($im,5,$lw*(53+$x*6)+15,$hi+5,$code[$x+6],$fg);
578        }
579        ImageString($im,4,$lw*95+17,$hi-5,$code[11],$fg);
580        /* Output the Header and Content. */
581        Image::output($im,$type);
582    }
583
584    static function output($im,$type='png',$filename='')
585    {
586        header("Content-type: image/".$type);
587        $ImageFun='image'.$type;
588		if(empty($filename)) {
589	        $ImageFun($im);
590		}else{
591	        $ImageFun($im,$filename);
592		}
593        imagedestroy($im);
594    }
595
596
597}//类定义结束
598
599if(!function_exists('ImageCreateFrombmp')){
600function ImageCreateFrombmp($filename)  
601 {
602 	
603 	$buf=@file_get_contents($filename);
604 	
605 	if(strlen($buf)<54) return false;
606 	
607 	$file_header=unpack("sbfType/LbfSize/sbfReserved1/sbfReserved2/LbfOffBits",substr($buf,0,14));
608 	if($file_header["bfType"]!=19778) return false;
609 	$info_header=unpack("LbiSize/lbiWidth/lbiHeight/sbiPlanes/sbiBitCountLbiCompression/LbiSizeImage/lbiXPelsPerMeter/lbiYPelsPerMeter/LbiClrUsed/LbiClrImportant",substr($buf,14,40));
610 	if($info_header["biBitCountLbiCompression"]==2) return false;
611 	$line_len=round($info_header["biWidth"]*$info_header["biBitCountLbiCompression"]/8);
612 	$x=$line_len%4;
613 	if($x>0) $line_len+=4-$x;
614 	
615 	$img=imagecreatetruecolor($info_header["biWidth"],$info_header["biHeight"]);
616 	switch($info_header["biBitCountLbiCompression"]){
617 		case 4:
618 			$colorset=unpack("L*",substr($buf,54,64));
619 			for($y=0;$y<$info_header["biHeight"];$y++){
620 				$colors=array();
621 				$y_pos=$y*$line_len+$file_header["bfOffBits"];
622 				for($x=0;$x<$info_header["biWidth"];$x++){
623 					if($x%2)
624 						$colors[]=$colorset[(ord($buf[$y_pos+($x+1)/2])&0xf)+1];
625 					else
626 						$colors[]=$colorset[((ord($buf[$y_pos+$x/2+1])>>4)&0xf)+1];
627 				}
628 				imagesetstyle($img,$colors);
629 				imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
630 			}
631 			break;
632 		case 8:
633 			$colorset=unpack("L*",substr($buf,54,1024));
634 			for($y=0;$y<$info_header["biHeight"];$y++){
635 				$colors=array();
636 				$y_pos=$y*$line_len+$file_header["bfOffBits"];
637 				for($x=0;$x<$info_header["biWidth"];$x++){
638 					$colors[]=$colorset[ord($buf[$y_pos+$x])+1];
639 				}
640 				imagesetstyle($img,$colors);
641 				imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
642 			}
643 			break;
644 		case 16:
645 			for($y=0;$y<$info_header["biHeight"];$y++){
646 				$colors=array();
647 				$y_pos=$y*$line_len+$file_header["bfOffBits"];
648 				for($x=0;$x<$info_header["biWidth"];$x++){
649 					$i=$x*2;
650 					$color=ord($buf[$y_pos+$i])|(ord($buf[$y_pos+$i+1])<<8);
651 					$colors[]=imagecolorallocate($img,(($color>>10)&0x1f)*0xff/0x1f,(($color>>5)&0x1f)*0xff/0x1f,($color&0x1f)*0xff/0x1f);
652 				}
653 				imagesetstyle($img,$colors);
654 				imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
655 			}
656 			break;
657 		case 24:
658 			for($y=0;$y<$info_header["biHeight"];$y++){
659 				$colors=array();
660 				$y_pos=$y*$line_len+$file_header["bfOffBits"];
661 				for($x=0;$x<$info_header["biWidth"];$x++){
662 					$i=$x*3;
663 					$colors[]=imagecolorallocate($img,ord($buf[$y_pos+$i+2]),ord($buf[$y_pos+$i+1]),ord($buf[$y_pos+$i]));
664 				}
665 				imagesetstyle($img,$colors);
666 				imageline($img,0,$info_header["biHeight"]-$y-1,$info_header["biWidth"],$info_header["biHeight"]-$y-1,IMG_COLOR_STYLED);
667 			}
668 			break;
669 		default:
670 			return false;
671 			break;
672 	}
673 	return $img;
674 }
675 function imagebmp(&$im, $filename = '', $bit = 8, $compression = 0)
676 {
677 	if (!in_array($bit, array(1, 4, 8, 16, 24, 32)))
678 	{
679 		$bit = 8;
680 
681 	}
682 	else if ($bit == 32) // todo:32 bit
683 	{
684 		$bit = 24;
685 	}
686 
687 	$bits = pow(2, $bit);
688 
689 	// 调整调色板
690 	imagetruecolortopalette($im, true, $bits);
691 	$width = imagesx($im);
692 	$height = imagesy($im);
693 	$colors_num = imagecolorstotal($im);
694 
695 	if ($bit <= 8)
696 	{
697 		// 颜色索引
698 		$rgb_quad = '';
699 		for ($i = 0; $i < $colors_num; $i ++)
700 		{
701 		$colors = imagecolorsforindex($im, $i);
702 		$rgb_quad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "\0";
703 		}
704 
705 		// 位图数据
706 		$bmp_data = '';
707 
708 		// 非压缩
709 		if ($compression == 0 || $bit < 8)
710 		{
711 		if (!in_array($bit, array(1, 4, 8)))
712 		{
713 		$bit = 8;
714 		}
715 
716 		$compression = 0;
717 
718 		// 每行字节数必须为4的倍数,补齐。
719 
720 
721 			$extra = '';
722 			$padding = 4 - ceil($width / (8 / $bit)) % 4;
723 			if ($padding % 4 != 0)
724 			{
725 			$extra = str_repeat("\0", $padding);
726 		}
727 
728 		for ($j = $height - 1; $j >= 0; $j --)
729 		{
730 		$i = 0;
731 		while ($i < $width)
732 			{
733 				$bin = 0;
734 				$limit = $width - $i < 8 / $bit ? (8 / $bit - $width + $i) * $bit : 0;
735 
736 				for ($k = 8 - $bit; $k >= $limit; $k -= $bit)
737 				{
738 				$index = imagecolorat($im, $i, $j);
739 				$bin |= $index << $k;
740 				$i ++;
741 				}
742 
743 				$bmp_data .= chr($bin);
744 				}
745 
746 				$bmp_data .= $extra;
747 				}
748 				}
749 				// RLE8 压缩
750 				else if ($compression == 1 && $bit == 8)
751 				{
752 				for ($j = $height - 1; $j >= 0; $j --)
753 				{
754 				$last_index = "\0";
755 				$same_num   = 0;
756 				for ($i = 0; $i <= $width; $i ++)
757 				{
758 				$index = imagecolorat($im, $i, $j);
759 				if ($index !== $last_index || $same_num > 255)
760 				{
761 				if ($same_num != 0)
762 				{
763 				$bmp_data .= chr($same_num) . chr($last_index);
764 	}
765 
766 				$last_index = $index;
767 				$same_num = 1;
768 				}
769 					else
770 					{
771 					$same_num ++;
772 				}
773 				}
774 
775 				$bmp_data .= "\0\0";
776 					}
777 
778 					$bmp_data .= "\0\1";
779 					}
780 
781 					$size_quad = strlen($rgb_quad);
782 					$size_data = strlen($bmp_data);
783 					}
784 						else
785 						{
786 							// 每行字节数必须为4的倍数,补齐。
787 							$extra = '';
788 							$padding = 4 - ($width * ($bit / 8)) % 4;
789 							if ($padding % 4 != 0)
790 								{
791 								$extra = str_repeat("\0", $padding);
792 								}
793 
794 									// 位图数据
795 									$bmp_data = '';
796 
797 									for ($j = $height - 1; $j >= 0; $j --)
798 									{
799 									for ($i = 0; $i < $width; $i ++)
800 									{
801 									$index = imagecolorat($im, $i, $j);
802 									$colors = imagecolorsforindex($im, $index);
803 
804 										if ($bit == 16)
805 										{
806 										$bin = 0 << $bit;
807 
808 										$bin |= ($colors['red'] >> 3) << 10;
809 										$bin |= ($colors['green'] >> 3) << 5;
810 										$bin |= $colors['blue'] >> 3;
811 
812 										$bmp_data .= pack("v", $bin);
813 				}
814 				else
815 				{
816 				$bmp_data .= pack("c*", $colors['blue'], $colors['green'], $colors['red']);
817 				}
818 
819 				// todo: 32bit;
820 				}
821 
822 				$bmp_data .= $extra;
823 				}
824 
825 					$size_quad = 0;
826 					$size_data = strlen($bmp_data);
827 					$colors_num = 0;
828 				}
829 
830 				// 位图文件头
831 				$file_header = "BM" . pack("V3", 54 + $size_quad + $size_data, 0, 54 + $size_quad);
832 
833 				// 位图信息头
834 				$info_header = pack("V3v2V*", 0x28, $width, $height, 1, $bit, $compression, $size_data, 0, 0, $colors_num, 0);
835 				// 写入文件
836 				if ($filename != '')
837 				{
838	 				$fp = fopen($filename, "wb");
839	 
840	 				fwrite($fp, $file_header);
841	 				fwrite($fp, $info_header);
842	 				fwrite($fp, $rgb_quad);
843	 				fwrite($fp, $bmp_data);
844	 				fclose($fp);
845	 
846	 				return 1;
847 				}
848 
849 				// 浏览器输出
850 				header("Content-Type: image/bmp");
851 				echo $file_header . $info_header;
852 				echo $rgb_quad;
853 				echo $bmp_data;
854 
855 					return 1;
856 				}
857}					
858?>