ProcessImage.class.php 2.6 KB
<?php
/**
 * 处理图片
 */
class Lib_Utils_ProcessImage
{
    /**
     * 创建文件夹
     * 
     * @param string $path
     * @return void
     */
    public static function createFolder($path)
    {
        if (! file_exists($path))
        {
            $path = dirname($path);
            self::createFolder($path);
            @mkdir($path, 0755);
        }
    }
    
    /**
     * 方法: 处理图片
     * 
     * @param integer $mode (第几种模式)
     * @param integer $size (剪切的尺寸)
     * @param string $source (源文件路径)
     * @param string $target (目标文件路径)
     * @return void
     */
    public static function process($mode, $size, $source, $target)
    {
        self::createFolder($target);
        list($w, $h) = explode('x', $size);
        
        $w = intval($w, 10);
        $h = intval($h, 10);
        $method = array_search($mode, Config_Static::$cropTypes);
        $image = new Util_Image_Gmagick($source);
        if($method == 'autoCrop')
        {
            // 缩略剪切
            $image->flatten()->crop($w, $h, -1, -1)->compress()->save($target);
        }
        else
        {
            $image->flatten()->$method($w, $h)->compress()->save($target);
        }
    }
    
    /**
     * 处理缩略图
     * 
     * @param array $thumbsFormat(缩略图规则)
     * @param string $thumbPathKey(缩略图存在方式: img01|img02)
     * @param string $projectPath(项目路径)
     * @param string $sourceFile (原图文件路径)
     * @param int $wait_microtime (等待时间,单位:微秒)
     * @return boolean
     */
    public static function processThumb($thumbsFormat, $thumbPathKey, $projectPath, $sourceFile, $wait_microtime = 1000)
    {
        if(empty($thumbsFormat))
        {
            return false;
        }
        foreach($thumbsFormat as $thumb)
        {
            $pos = strrpos($sourceFile, '.');
            $mode = Config_Static::$cropTypes[$thumb['mode']];
            $parts['left'] = substr($sourceFile, 0, $pos);
            $parts['right'] = substr($sourceFile, $pos);
            $path = Config_File_Image::$imageServer[$thumbPathKey].$projectPath;
            $dest = Config_File_Image::$thumbPath[$thumbPathKey].$projectPath;
            $dest .= $parts['left'] . '-' . str_pad($thumb['w'], 4, '0', STR_PAD_LEFT) 
                            . 'x' . str_pad($thumb['h'], 4, '0', STR_PAD_LEFT) 
                            . '-' . $mode . $parts['right'];          
            self::process($mode, $thumb['w'].'x'.$thumb['h'], $path.$sourceFile, $dest);
            usleep($wait_microtime);
        }
         return true;
    }
}