如何使用边缘周围的白色边框将图像放大到 900x1200?

时间:2021-03-02 16:43:33

标签: python

我需要将图像放大或缩小到 900x1200 的纵横比,但这样它就不会拉伸,也就是说,它在边缘的白边的帮助下增长。请告诉我该怎么做?

有关于如何执行此操作的代码,但最终结果是 900x900 或 1200x1200,但我正好需要 900x1200

target_width = 900
      target_height = 1200

        for subdir, dirs, files in os.walk('CATALOGUE/images_new/'):
            if subdir != 'CATALOGUE/images_new/':
                for img in files:
                    img = Image.open(subdir + '/' + img)

                    target_ratio = target_height / target_width
                    img_ratio = img.height / img.width
                    if target_ratio > img_ratio:
                        resize_width = target_width
                        resize_height = round(resize_width * img_ratio)
                    else:
                        resize_height = target_height
                        resize_width = round(resize_height / img_ratio)

                    image_resize = img.resize((resize_width, resize_height), Image.ANTIALIAS)
                    background = Image.new('RGBA', (target_width, target_height), (255, 255, 255, 255))
                    offset = (round((target_width - resize_width) / 2), round((target_height - resize_height) / 2))
                    background.paste(image_resize, offset)

0 个答案:

没有答案
相关问题