有谁能提供在djang中合并两个图像的代码吗

2024-10-04 07:38:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用django合并两个图像。但我不成功,请任何一个给我提供代码合并两个图像,这样,一个图像应该放在另一个,并保存为.jpg。我的邮件id是srikanthmadireddy78@gamil.com你知道吗


Tags: django代码图像comid邮件jpggamil
1条回答
网友
1楼 · 发布于 2024-10-04 07:38:09

您可以使用Python Imaging Library。你知道吗

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合并时。你知道吗

相关问题 更多 >