dongzhou1865 2017-03-04 17:19
浏览 138
已采纳

将图像从中心裁剪成Yii2 Imagine中可以制作的最大正方形?

I'm using the Yii2 extension Imagine and I need to make 150x150 images from user uploads.

Currently I am just doing something like this:

use yii\imagine\Image;

....

Image::thumbnail($save_path, $img_size, $img_size)->save($save_path);

Obviously this can cause issues if one of the dimensions is < 150px once resized.

So what I'm trying to primarily figure out is how to crop the image into a square before it is resized, so that when I resize it there won't be any aspect ratio issues.

Now, I know you can crop the image with something like:

Image::crop($save_path, $img_size, $img_size, [5, 5]);

But problem is doing this before resizing the image will likely not give you what you want since the image may be so large and cropping it after resizing won't work either as one dimension may already have been reduced to < 150px.

So what I'm trying to work out is how can I crop the image before resizing to the maximum size square possible and from the center out?

Edit:

Ok, I have worked out a way to handle this, but was wondering if there was anyway to accomplish the below easily or will I need to code it myself?

  • Work out the smallest dimension (width or height)
  • Then take that dimension and that will be the largest square you can have
  • Work out how to position that in the center for the crop
  • Now you can do the resize
  • If after the resize either side is smaller than 150, create new white background image and then center the new image on that
  • Save image
  • Done!
  • 写回答

2条回答 默认 最新

  • douzhong1907 2017-03-12 20:14
    关注

    Another try :p

    <?php
    
    use yii\imagine\Image;
    use Imagine\Image\Box;
    use Imagine\Image\Point;
    
    // ...
    
    $thumbnail = Image::thumbnail($save_path, $img_size, $img_size);
    $size = $thumbnail->getSize();
    if ($size->getWidth() < $img_size or $size->getHeight() < $img_size) {
        $white = Image::getImagine()->create(new Box($img_size, $img_size));
        $thumbnail = $white->paste($thumbnail, new Point($img_size / 2 - $size->getWidth() / 2, $img_size / 2 - $size->getHeight() / 2));
    }
    $thumbnail->save($save_path);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能