PageRenderTime 53ms CodeModel.GetById 12ms app.highlight 33ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Tpblog/ThinkPHP/Lib/ORG/Util/Image.class.php

http://tpblog.googlecode.com/
PHP | 508 lines | 292 code | 30 blank | 186 comment | 52 complexity | d344f16b29e1c2e81070847e69a04e52 MD5 | raw file
  1<?php
  2// +----------------------------------------------------------------------
  3// | ThinkPHP
  4// +----------------------------------------------------------------------
  5// | Copyright (c) 2008 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 extends Base
 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            if(function_exists(image_type_to_extension)){
 44                $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]),1));
 45            }else{
 46                $imageType = strtolower(substr($img,strrpos($img,'.')+1));
 47            }
 48            $imageSize = filesize($img);
 49            $info = array(
 50                "width"=>$imageInfo[0],
 51                "height"=>$imageInfo[1],
 52                "type"=>$imageType,
 53                "size"=>$imageSize,
 54                "mime"=>$imageInfo['mime']
 55            );
 56            return $info;
 57        }else {
 58            return false;
 59        }
 60    }
 61
 62    /**
 63     +----------------------------------------------------------
 64     * ?????????
 65     * ??URL??
 66     +----------------------------------------------------------
 67     * @static
 68     * @access public
 69     +----------------------------------------------------------
 70     * @param string $imgFile ?????
 71     * @param string $text ?????
 72     * @param string $width ????
 73     * @param string $height ????
 74     +----------------------------------------------------------
 75     * @return void
 76     +----------------------------------------------------------
 77     */
 78    static function showImg($imgFile,$text='',$width=80,$height=30) {
 79        //????????
 80        $info = Image::getImageInfo($imgFile);
 81        if($info !== false) {
 82            $createFun  =   str_replace('/','createfrom',$info['mime']);
 83            $im = $createFun($imgFile);
 84            if($im) {
 85                $ImageFun= str_replace('/','',$info['mime']);
 86                if(!empty($text)) {
 87                    $tc  = imagecolorallocate($im, 0, 0, 0);
 88                    imagestring($im, 3, 5, 5, $text, $tc);
 89                }
 90                if($info['type']=='png' || $info['type']=='gif') {
 91                imagealphablending($im, false);//?????????
 92                imagesavealpha($im,true);//??????? alpha ????
 93                }
 94                Header("Content-type: ".$info['mime']);
 95                $ImageFun($im);
 96                @ImageDestroy($im);
 97                return ;
 98            }
 99        }
100        //?????????????????PNG??
101        $im  = imagecreatetruecolor($width, $height);
102        $bgc = imagecolorallocate($im, 255, 255, 255);
103        $tc  = imagecolorallocate($im, 0, 0, 0);
104        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
105        imagestring($im, 4, 5, 5, "NO PIC", $tc);
106        Image::output($im);
107        return ;
108    }
109
110    /**
111     +----------------------------------------------------------
112     * ?????
113     +----------------------------------------------------------
114     * @static
115     * @access public
116     +----------------------------------------------------------
117     * @param string $image  ??
118     * @param string $type ????
119     * @param string $filename ??????
120     * @param string $maxWidth  ??
121     * @param string $maxHeight  ??
122     * @param string $position ???????
123     * @param boolean $interlace ??????
124     +----------------------------------------------------------
125     * @return void
126     +----------------------------------------------------------
127     * @throws ThinkExecption
128     +----------------------------------------------------------
129     */
130    static function thumb($image,$type='',$filename='',$maxWidth=200,$maxHeight=50,$interlace=true,$suffix='_thumb')
131    {
132        // ??????
133        $info  = Image::getImageInfo($image);
134         if($info !== false) {
135            $srcWidth  = $info['width'];
136            $srcHeight = $info['height'];
137            $pathinfo = pathinfo($image);
138            $type =  $pathinfo['extension'];
139            $type = empty($type)?$info['type']:$type;
140            $type = strtolower($type);
141            $interlace  =  $interlace? 1:0;
142            unset($info);
143            $scale = min($maxWidth/$srcWidth, $maxHeight/$srcHeight); // ??????
144            if($scale>=1) {
145                // ??????????
146                $width   =  $srcWidth;
147                $height  =  $srcHeight;
148            }else{
149                // ?????
150                $width  = (int)($srcWidth*$scale);
151                $height = (int)($srcHeight*$scale);
152            }
153
154            // ????
155            $createFun = 'ImageCreateFrom'.($type=='jpg'?'jpeg':$type);
156            $srcImg     = $createFun($image);
157
158            //?????
159            if($type!='gif' && function_exists('imagecreatetruecolor'))
160                $thumbImg = imagecreatetruecolor($width, $height);
161            else
162                $thumbImg = imagecreate($width, $height);
163
164            // ????
165            if(function_exists("ImageCopyResampled"))
166                ImageCopyResampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth,$srcHeight);
167            else
168                ImageCopyResized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height,  $srcWidth,$srcHeight);
169            if('gif'==$type || 'png'==$type) {
170                //imagealphablending($thumbImg, false);//?????????
171                //imagesavealpha($thumbImg,true);//??????? alpha ????
172                $background_color  =  imagecolorallocate($thumbImg,  0,255,0);  //  ??????
173                imagecolortransparent($thumbImg,$background_color);  //  ????????????????????
174            }
175
176            // ?jpeg????????
177            if('jpg'==$type || 'jpeg'==$type)   imageinterlace($thumbImg,$interlace);
178
179            //$gray=ImageColorAllocate($thumbImg,255,0,0);
180            //ImageString($thumbImg,2,5,5,"ThinkPHP",$gray);
181            // ????
182            $imageFun = 'image'.($type=='jpg'?'jpeg':$type);
183            $filename  = empty($filename)? substr($image,0,strrpos($image, '.')).$suffix.'.'.$type : $filename;
184
185            $imageFun($thumbImg,$filename);
186            ImageDestroy($thumbImg);
187            ImageDestroy($srcImg);
188            return $filename;
189         }
190         return false;
191    }
192
193    /**
194     +----------------------------------------------------------
195     * ???????
196     +----------------------------------------------------------
197     * @static
198     * @access public
199     +----------------------------------------------------------
200     * @param string $length  ??
201     * @param string $mode  ??
202     * @param string $type ????
203     * @param string $width  ??
204     * @param string $height  ??
205     +----------------------------------------------------------
206     * @return string
207     +----------------------------------------------------------
208     * @throws ThinkExecption
209     +----------------------------------------------------------
210     */
211    static function buildImageVerify($length=4,$mode=1,$type='png',$width=48,$height=22,$verifyName='verify')
212    {
213        $randval = build_verify($length,$mode);
214        $_SESSION[$verifyName]= md5($randval);
215        $width = ($length*9+10)>$width?$length*9+10:$width;
216        if ( $type!='gif' && function_exists('imagecreatetruecolor')) {
217            $im = @imagecreatetruecolor($width,$height);
218        }else {
219            $im = @imagecreate($width,$height);
220        }
221        $r = Array(225,255,255,223);
222        $g = Array(225,236,237,255);
223        $b = Array(225,236,166,125);
224        $key = mt_rand(0,3);
225
226        $backColor = imagecolorallocate($im, $r[$key],$g[$key],$b[$key]);    //???????
227        $borderColor = imagecolorallocate($im, 100, 100, 100);                    //???
228        $pointColor = imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));                 //???
229
230        @imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
231        @imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
232        $stringColor = imagecolorallocate($im,mt_rand(0,200),mt_rand(0,120),mt_rand(0,120));
233        // ??
234        for($i=0;$i<10;$i++){
235            $fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
236            imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$fontcolor);
237        }
238        for($i=0;$i<25;$i++){
239            $fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
240            imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pointColor);
241        }
242
243        @imagestring($im, 5, 5, 3, $randval, $stringColor);
244        Image::output($im,$type);
245    }
246
247    // ?????
248    static function GBVerify($length=4,$type='png',$width=180,$height=50,$fontface='simhei.ttf',$verifyName='verify') {
249        $code   =   rand_string($length,4);
250        $width = ($length*45)>$width?$length*45:$width;
251        $_SESSION[$verifyName]= md5($code);
252        $im=imagecreatetruecolor($width,$height);
253        $borderColor = imagecolorallocate($im, 100, 100, 100);                    //???
254        $bkcolor=imagecolorallocate($im,250,250,250);
255        imagefill($im,0,0,$bkcolor);
256        @imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
257        // ??
258        for($i=0;$i<15;$i++){
259            $fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
260            imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$fontcolor);
261        }
262        for($i=0;$i<255;$i++){
263            $fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
264            imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$fontcolor);
265        }
266        if(!is_file($fontface)) {
267            $fontface = dirname(__FILE__)."/".$fontface;
268        }
269        for($i=0;$i<$length;$i++){
270            $fontcolor=imagecolorallocate($im,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120)); //??????????????
271            $codex= msubstr($code,$i,1);
272            imagettftext($im,mt_rand(16,20),mt_rand(-60,60),40*$i+20,mt_rand(30,35),$fontcolor,$fontface,$codex);
273        }
274        Image::output($im,$type);
275    }
276
277    /**
278     +----------------------------------------------------------
279     * ??????????
280     +----------------------------------------------------------
281     * @static
282     * @access public
283     +----------------------------------------------------------
284     * @param string $image  ??????
285     * @param string $type  ???????????
286     +----------------------------------------------------------
287     * @return string
288     +----------------------------------------------------------
289     * @throws ThinkExecption
290     +----------------------------------------------------------
291     */
292    static function showASCIIImg($image,$string='',$type='')
293    {
294        $info  = Image::getImageInfo($image);
295        if($info !== false) {
296            $type = empty($type)?$info['type']:$type;
297            unset($info);
298            // ????
299            $createFun = 'ImageCreateFrom'.($type=='jpg'?'jpeg':$type);
300            $im     = $createFun($image);
301            $dx = imagesx($im);
302            $dy = imagesy($im);
303            $i  =   0;
304            $out   =  '<span style="padding:0px;margin:0;line-height:100%;font-size:1px;">';
305            set_time_limit(0);
306            for($y = 0; $y < $dy; $y++) {
307              for($x=0; $x < $dx; $x++) {
308                  $col = imagecolorat($im, $x, $y);
309                  $rgb = imagecolorsforindex($im,$col);
310                  $str   =   empty($string)?'*':$string[$i++];
311                  $out .= sprintf('<span style="margin:0px;color:#%02x%02x%02x">'.$str.'</span>',$rgb['red'],$rgb['green'],$rgb['blue']);
312             }
313             $out .= "<br>\n";
314            }
315            $out .=  '</span>';
316            imagedestroy($im);
317            return $out;
318        }
319        return false;
320    }
321
322    /**
323     +----------------------------------------------------------
324     * ?????????
325     +----------------------------------------------------------
326     * @static
327     * @access public
328     +----------------------------------------------------------
329     * @param string $type ????
330     * @param string $width  ??
331     * @param string $height  ??
332     +----------------------------------------------------------
333     * @return string
334     +----------------------------------------------------------
335     * @throws ThinkExecption
336     +----------------------------------------------------------
337     */
338    static function showAdvVerify($type='png',$width=180,$height=40)
339    {
340        $rand   =   range('a','z');
341        shuffle($rand);
342        $verifyCode =   array_slice($rand,0,10);
343        $letter = implode(" ",$verifyCode);
344        $_SESSION['verifyCode'] = $verifyCode;
345        $im = imagecreate($width,$height);
346        $r = array(225,255,255,223);
347        $g = array(225,236,237,255);
348        $b = array(225,236,166,125);
349        $key = mt_rand(0,3);
350        $backColor = imagecolorallocate($im, $r[$key],$g[$key],$b[$key]);
351        $borderColor = imagecolorallocate($im, 100, 100, 100);                    //???
352        imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
353        imagerectangle($im, 0, 0, $width-1, $height-1, $borderColor);
354        $numberColor = imagecolorallocate($im, 255,rand(0,100), rand(0,100));
355        $stringColor = imagecolorallocate($im, rand(0,100), rand(0,100), 255);
356        // ????
357        for($i=0;$i<10;$i++){
358            $fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
359            imagearc($im,mt_rand(-10,$width),mt_rand(-10,$height),mt_rand(30,300),mt_rand(20,200),55,44,$fontcolor);
360        }
361        for($i=0;$i<255;$i++){
362            $fontcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
363            imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$fontcolor);
364        }
365        imagestring($im, 5, 5, 1, "0 1 2 3 4 5 6 7 8 9", $numberColor);
366        imagestring($im, 5, 5, 20, $letter, $stringColor);
367        Image::output($im,$type);
368    }
369
370    /**
371     +----------------------------------------------------------
372     * ??UPC-A???
373     +----------------------------------------------------------
374     * @static
375     +----------------------------------------------------------
376     * @param string $type ????
377     * @param string $type ????
378     * @param string $lw  ????
379     * @param string $hi   ????
380     +----------------------------------------------------------
381     * @return string
382     +----------------------------------------------------------
383     * @throws ThinkExecption
384     +----------------------------------------------------------
385     */
386    static function UPCA($code,$type='png',$lw=2,$hi=100) {
387        static $Lencode = array('0001101','0011001','0010011','0111101','0100011',
388                         '0110001','0101111','0111011','0110111','0001011');
389        static $Rencode = array('1110010','1100110','1101100','1000010','1011100',
390                         '1001110','1010000','1000100','1001000','1110100');
391        $ends = '101';
392        $center = '01010';
393        /* UPC-A Must be 11 digits, we compute the checksum. */
394        if ( strlen($code) != 11 ) { die("UPC-A Must be 11 digits."); }
395        /* Compute the EAN-13 Checksum digit */
396        $ncode = '0'.$code;
397        $even = 0; $odd = 0;
398        for ($x=0;$x<12;$x++) {
399          if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; }
400        }
401        $code.=(10 - (($odd * 3 + $even) % 10)) % 10;
402        /* Create the bar encoding using a binary string */
403        $bars=$ends;
404        $bars.=$Lencode[$code[0]];
405        for($x=1;$x<6;$x++) {
406          $bars.=$Lencode[$code[$x]];
407        }
408        $bars.=$center;
409        for($x=6;$x<12;$x++) {
410          $bars.=$Rencode[$code[$x]];
411        }
412        $bars.=$ends;
413        /* Generate the Barcode Image */
414        if ( $type!='gif' && function_exists('imagecreatetruecolor')) {
415            $im = imagecreatetruecolor($lw*95+30,$hi+30);
416        }else {
417            $im = imagecreate($lw*95+30,$hi+30);
418        }
419        $fg = ImageColorAllocate($im, 0, 0, 0);
420        $bg = ImageColorAllocate($im, 255, 255, 255);
421        ImageFilledRectangle($im, 0, 0, $lw*95+30, $hi+30, $bg);
422        $shift=10;
423        for ($x=0;$x<strlen($bars);$x++) {
424          if (($x<10) || ($x>=45 && $x<50) || ($x >=85)) { $sh=10; } else { $sh=0; }
425          if ($bars[$x] == '1') { $color = $fg; } else { $color = $bg; }
426          ImageFilledRectangle($im, ($x*$lw)+15,5,($x+1)*$lw+14,$hi+5+$sh,$color);
427        }
428        /* Add the Human Readable Label */
429        ImageString($im,4,5,$hi-5,$code[0],$fg);
430        for ($x=0;$x<5;$x++) {
431          ImageString($im,5,$lw*(13+$x*6)+15,$hi+5,$code[$x+1],$fg);
432          ImageString($im,5,$lw*(53+$x*6)+15,$hi+5,$code[$x+6],$fg);
433        }
434        ImageString($im,4,$lw*95+17,$hi-5,$code[11],$fg);
435        /* Output the Header and Content. */
436        Image::output($im,$type);
437    }
438
439    /**
440     +----------------------------------------------------------
441     * ???????
442     +----------------------------------------------------------
443     * @static public
444     +----------------------------------------------------------
445     * @param string $source ????
446     * @param string $water  ????
447     * @param string $$savename  ?????????
448     * @param string $alpha  ??????
449     +----------------------------------------------------------
450     * @return string
451     +----------------------------------------------------------
452     * @throws ThinkExecption
453     +----------------------------------------------------------
454     */
455
456    static public function water($source,$water,$savename=null,$alpha=80)
457    {
458        //????????
459        if(!file_exists($source)||!file_exists($water))
460            return false;
461
462        //????
463        $sInfo=self::getImageInfo($source);
464        $wInfo=self::getImageInfo($water);
465
466        //????????????????
467        if($sInfo["width"]<$wInfo["width"] || $sInfo['height']<$wInfo['height'])
468            return false;
469
470        //????
471        $sCreateFun="imagecreatefrom".$sInfo['type'];
472        $sImage=$sCreateFun($source);
473        $wCreateFun="imagecreatefrom".$wInfo['type'];
474        $wImage=$wCreateFun($water);
475
476        //?????????
477        imagealphablending($wImage, true);
478
479        //????,?????????
480        $posY=$sInfo["height"]-$wInfo["height"];
481        $posX=$sInfo["width"]-$wInfo["width"];
482
483        //??????
484         imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo['width'],$wInfo['height'],$alpha);
485
486        //????
487        $ImageFun='Image'.$sInfo['type'];
488        //???????????????????
489        if(!$savename){
490            $savename=$source;
491            @unlink($source);
492        }
493        //????
494        $ImageFun($sImage,$savename);
495        imagedestroy($sImage);
496
497    }
498
499    static function output($im,$type='png')
500    {
501        header("Content-type: image/".$type);
502        $ImageFun='Image'.$type;
503        $ImageFun($im);
504        imagedestroy($im);
505    }
506
507}//?????
508?>