codeigniter image_lib问题?

时间:2011-08-07 21:56:56

标签: php image codeigniter crop

$this->load->library('image_lib');
if($imgWidth > $imgHeight){
    $img['image_library'] = 'gd2';
    $img['source_image'] = 'uploads/img/gallery/small/'.$photo;
    $img['maintain_ratio'] = FALSE;
    $img['x_axis'] = $imgWidth - $imgHeight;
    $img['y_axis'] = 0;
    $this->image_lib->initialize($img);
    $this->image_lib->crop();
    echo $this->image_lib->display_errors();
}
if($imgWidth < $imgHeight){
    $img['image_library'] = 'gd2';
    $img['source_image'] = 'uploads/img/gallery/small/'.$photo;
    $img['create_thumb'] = TRUE;
    $img['dinamic_output'] = TRUE;
    $img['maintain_ratio'] = FALSE;

    $img['x_axis'] = 0;
    $img['y_axis'] = $imgHeight-$imgWidth;
    $this->image_lib->initialize($img);
    $this->image_lib->crop();

    echo $this->image_lib->display_errors();
}
$img['image_library'] = 'gd2';
$img['source_image'] = 'uploads/img/gallery/small/'.$photo;
$img['maintain_ratio'] = FALSE;
$img['width'] = 80;
$img['height'] = 80;
$this->image_lib->initialize($img);
$this->image_lib->resize();
echo $this->image_lib->display_errors();

为什么还没有裁剪但只是调整大小? :(

它也不会返回任何错误:/

1 个答案:

答案 0 :(得分:1)

好的,所以我做了一个重构,让你更好地了解发生了什么。我添加了评论以解释我的更改。

private function getBaseImgArray( $photo )
{
    // you need this array three times. It should be extracted.
    $ret = array(
        'image_library'  => 'gd2',
        'source_image'   => 'uploads/img/gallery/small/'.$photo,
        'maintain_ratio' => FALSE
    );
    return $ret;
}

private function getCroppedImgArray( $photo, $imgWidth, $imgHeight )
{
    // this summarizes everything in your first two code blocks.
    $img = $this->getBaseImgArray( $photo );
    $img[ 'x_axis' ] = ($imgWidth > $imgHeight)? $imgWidth - $imgHeight: 0;
    $img[ 'y_axis' ] = ($imgWidth < $imgHeight)? $imgHeight - $imgWidth: 0;
}

public function yourFunctionNameHere()
{
    $this->load->library('image_lib');
    $img = $this->getCroppedImgArray( $photo, $imgWidth, $imgHeight );

    // this is the only difference between the first and second img 
    // height/width blocks. Should it be there for both?
    if($imgWidth < $imgHeight){
        $img['create_thumb'] = TRUE;
    }

    $this->image_lib->initialize($img);
    $this->image_lib->crop();
    echo $this->image_lib->display_errors();

    // right here you're overwriting the above code. If your image library 
    // works as I would expect, then your cropped images will be cropped
    // overwritten, and then re-sized.
    $img = $this->getBaseImgArray( $photo );
    // on a technical note, you are using the same array when you resize,
    // but since resize ignores the <x/y>_axis variables, it would not effect
    // the final outcome.
    $img['width'] = 80;
    $img['height'] = 80;
    $this->image_lib->initialize($img);
    $this->image_lib->resize();
    echo $this->image_lib->display_errors();
}