在Codeigniter中将缩略图图像裁剪为正方形

时间:2017-01-01 17:34:27

标签: php css image codeigniter

我正在将一些图片上传到我的网页,并希望他们的缩略图是从中心裁剪的正方形。我正在使用Codeigniter和gd2。

到目前为止,这是我的代码:

$config['image_library'] = 'gd2';
                    $config['source_image'] = $this->userlibrary->picturesdir . $newfilename;
$config['new_image'] = $this->userlibrary->thumbsdir;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width']= 150;
$config['height']= 150;

图像可以很好地缩放,但它们保持纵横比,只有它们的宽度或高度设置为150,它们不会被裁剪。 设置maintain_ratio仍然不会裁剪图像,而是将其倾斜。

我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

超级迟到的响应,但是当我寻找相同的东西时,我遇到了这篇文章。以为我会与其他寻求相同解决方案的人分享我的解决方案。

        $config['source_image'] = 'path/to/image';

        //Find smallest dimension
        $imageSize = $this->image_lib->get_image_properties($config['source_image'], TRUE);
        $newSize = min($imageSize);

        $config['image_library'] = 'gd2';
        $config['width'] = $newSize;
        $config['height'] = $newSize;
        $config['y_axis'] = ($imageSize['height'] - $newSize) / 2;
        $config['x_axis'] = ($imageSize['width'] - $newSize) / 2;

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

        if(!$this->image_lib->crop())
        {
            echo $this->image_lib->display_errors();
        }

答案 1 :(得分:1)

//Set config for img library
$config['image_library'] = 'ImageMagick';
$config['library_path'] = '/usr/bin/';
$config['source_image'] = $filePath . $fileOldName;
$config['maintain_ratio'] = false;

//Set cropping for y or x axis, depending on image orientation
if ($fileData['image_width'] > $fileData['image_height']) {
    $config['width'] = $fileData['image_height'];
    $config['height'] = $fileData['image_height'];
    $config['x_axis'] = (($fileData['image_width'] / 2) - ($config['width'] / 2));
}
else {
    $config['height'] = $fileData['image_width'];
    $config['width'] = $fileData['image_width'];
    $config['y_axis'] = (($fileData['image_height'] / 2) - ($config['height'] / 2));
}

//Load image library and crop
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
if ($this->image_lib->crop()) {
    $error = $this->image_lib->display_errors();
}

//Clear image library settings so we can do some more image 
//manipulations if we have to
$this->image_lib->clear();
unset($config);

来源: https://forum.codeigniter.com/thread-7286.html