任何人都可以提供在django中合并两个图像的代码吗



我尝试在django中合并两个图像。但我没有成功,请任何人给我提供合并两个图像的代码,这样,一个图像应该放在另一个图像上,并保存为.jpg。我的邮件id是srikanthmadireddy78@gamil.com

您可以使用Python图像库。

from PIL import Image
def merge_img(background, foreground):
    #Conver both images to same color mode
    if background.mode != 'RGBA':
        background = background.convert('RGBA')
    if foreground.mode != 'RGBA':
        foreground = foreground.convert('RGBA')
    layer = Image.new('RGBA', background.size, (0,0,0,0))
    #Scale images
    ratio = min(float(background.size[0]) / foreground.size[0], float(background.size[1]) / foreground.size[1])
    w = int(foreground.size[0] * ratio)
    h = int(foreground.size[1] * ratio)
    foreground = foreground.resize((w, h))
    #Paste foreground at the middle of background
    layer.paste(foreground, ((background.size[0] - w) // 2, (background.size[1] - h) // 2))
    return Image.composite(layer, background, layer)

background = Image.open('background.jpg')
foreground = Image.open('foreground.jpg')
img = merge_img(background, foreground)
img.save('merged.jpg')

不一定要使用layerImage.composite(),你只能与paste()相处,但它们将有助于解决许多问题。尤其是需要将gif与jpeg合并时。

最新更新