首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >django-photologue:如何将图像缩放到方框和填充背景

django-photologue:如何将图像缩放到方框和填充背景
EN

Stack Overflow用户
提问于 2011-02-14 03:26:18
回答 1查看 324关注 0票数 0

我正在使用django-photologue (带1pinax),并希望将图像缩放到一个框(100px X 100px)。肖像图像应缩放到高度100px,宽度应填充颜色。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-02-14 05:15:48

您可以将PIL与转换矩阵一起使用。例如,下面的函数在一次操作中调整大小和裁剪。就我个人而言,我更喜欢裁剪而不是填充颜色,但您可以根据需要进行调整。

代码语言:javascript
复制
def resize_and_crop(im, mask_width=1000, mask_height=1000):
    width, height = im.size
    aspect = 1.0*width/height
    mask_aspect = 1.0*mask_width/mask_height
    if width != mask_width or height != mask_height:
        if aspect > mask_aspect:
            ratio = 1.0*height/mask_height
            imt = im.transform((mask_width, mask_height), 
                                Image.AFFINE, 
                               (ratio, 0, (width-mask_width*ratio)/2, 0, ratio, 0),
                               Image.CUBIC)
        else:
            ratio = 1.0*width/mask_width
            imt = im.transform((mask_width, mask_height), 
                               Image.AFFINE, 
                               (ratio, 0, 0, 0, ratio, (height-mask_height*ratio)/2),
                               Image.CUBIC)
    else:
        imt = im
    return imt
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4986320

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档