Codeigniter图像类的简单解决方案?

时间:2013-10-07 13:19:14

标签: codeigniter image-processing

我有一些凌乱的代码,即使我使用SimpleImage,我知道我可以使用CodeIgniter图像类,但配置有点大,可以有人发布一个优雅和更好的解决方案,这是我现在的代码,我想得到摆脱SimpleImage,并在控制器中初始化图像类。这就是我所拥有的:

// Main config
$config['image_library'] = 'gd2';
$config['maintain_ratio'] = TRUE;
$config['height'] = '1';
$config['master_dim'] = 'width';
$config['overwrite'] = TRUE;

// Resize image with SimpleImage
$novaslika="img/proizvodi/".$last.".jpg";
$image = new SimpleImage();
$image->load($_FILES['slika']['tmp_name']);
$image->resizeToWidth(800);
$image->save($novaslika);

// Create PNG 
$config['source_image'] = $_FILES['maska']['tmp_name'];
$config['width']     = 800;
$config['new_image']    = "./img/proizvodi/".$last."_maska.png";
$this->image_lib->initialize($config);
$this->image_lib->resize(); 

// Create thumb
$config['source_image'] = './img/proizvodi/'.$last.'.jpg';
$config['create_thumb'] = TRUE;
$config['new_image']    = './img/proizvodi/thumbs/'.$last.'_thumb.jpg';
$this->image_lib->initialize($config);
$this->image_lib->resize();

1 个答案:

答案 0 :(得分:0)

您可以这样做:

function index()
{
    $this->load->library('image_lib');

    $a = array(
        'source_image' => 'images/1.jpg',
        'width' => 100,
        'height' => 100,
        'new_image' => 'images/2.jpg',
        'create_thumb' => TRUE,
        'overwrite' => FALSE
    );


    $image = $this->_image_manipulation($a);

    if($image === TRUE)
    {
        echo "IMAGE OK";
    }
    else
    {
        echo $image;
    }

}

private function _image_manipulation($configs = '')
{
    if($configs)
    {
        $config['image_library'] = 'gd2';   //static
        $config['maintain_ratio'] = TRUE;   //static
        $config['master_dim'] = 'width';    //static

        $config['source_image'] = $configs['source_image'];//required

        $config['height']       = (isset($configs['height']))?$configs['height']:NULL;          
        $config['width']        = (isset($configs['width']))?$configs['width']:NULL;

        $config['overwrite']    = (isset($configs['overwrite']))?$configs['overwrite']:NULL;

        $config['new_image']    = (isset($configs['new_image']))?$configs['new_image']:NULL;
        $config['create_thumb'] = (isset($configs['create_thumb']))?$configs['create_thumb']:NULL;

        $this->image_lib->initialize($config);

        if ( ! $this->image_lib->resize())
        {
            return $this->image_lib->display_errors();
        }
        else
        {
            return TRUE;
        }
    }
}

但是仍然需要SimpleImage库转换为png的 UNLESS ,我无法确认,SimpleImage正在使用ImageMagick。如果是,这意味着它已安装在系统上,您可以更改

$config['image_library'] = 'gd2';

$config['image_library'] = 'ImageMagick';

和CodeIgniter也将为您处理图像转换;您需要做的就是重命名文件:

$a = array(
    'source_image' => 'images/1.jpg',
    'new_image' => 'images/1.png',
);