【问题标题】:django-photologue: How to scale image to box and fill backgrounddjango-photologue:如何将图像缩放到框并填充背景
【发布时间】:2011-02-13 19:26:18
【问题描述】:

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

【问题讨论】:

    标签: python django python-imaging-library pinax


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 2015-10-17
      相关资源
      最近更新 更多