python如何把一个png中不透明的部分缩小再与另一个图片为背景全成一张图?

2023-06-30 351 0

一个png中不透明的部分缩小部分要求放在另一张图片的指点坐标处,比如x,y都居中

from PIL import Image, ImageDraw, ImageFont
def add_watermark(img_path, watermark_path):
    # 加载主图片
    main_img = Image.open(img_path).convert('RGBA')
    main_width, main_height = main_img.size
    # 加载水印图片
    watermark_img = Image.open(watermark_path).convert('RGBA')
    watermark_width, watermark_height = watermark_img.size
    # 水印图片缩小一半
    scale = 0.5
    new_size = (int(watermark_width * scale), int(watermark_height * scale))
    # 改变图像大小
    new_img = watermark_img.resize(new_size)
    width, height = new_img.size
    # 创建画布
    position = (int((main_width - width)/2), int((main_height - height)/2))
    watermark_canvas = Image.new('RGBA', main_img.size, (0, 0, 0, 0))
    watermark_canvas.paste(new_img, position)
    # 合并图片
    result_img = Image.alpha_composite(main_img, watermark_canvas)
    # 保存图片
    result_path = img_path.split('/')[-1].split('.')[0] + '_with_watermark.png'
    result_img.save(result_path)
    print('Watermark added successfully to the image: ', result_path)
add_watermark('./main.webp', './water.png')

要将一个PNG图像中不透明的部分缩小,并与另一张背景图片合并,你可以使用Python的PIL库(Pillow)来实现。下面是一个示例代码:
from PIL import Image

打开PNG图像和背景图像

foreground_image = Image.open('foreground.png')
background_image = Image.open('background.png')

缩小前景图像的尺寸

width, height = foreground_image.size
scaled_width, scaled_height = int(width/2), int(height/2)
scaled_foreground = foreground_image.resize((scaled_width, scaled_height))

在背景图像上创建一个新的图像对象

merged_image = background_image.copy()

计算将缩小后的前景图像放置在背景图像中心的坐标

center_x = (background_image.width - scaled_width) // 2
center_y = (background_image.height - scaled_height) // 2

将缩小后的前景图像粘贴到背景图像上

merged_image.paste(scaled_foreground, (center_x, center_y), mask=scaled_foreground)

保存合并后的图像

merged_image.save('merged_image.png')

请确保将"foreground.png"替换为你的PNG图像文件名,"background.png"替换为你的背景图像文件名。这段代码将打开前景图像和背景图像,将前景图像缩小一半,并将其放置在背景图像中央,然后保存合并后的图像为"merged_image.png"。

回答

相关文章

nuxt2部署静态化和ssr的时候访问首页先报404再出现首页为什么?
`clip-path` 如何绘制圆角平行四边形呢?
多线程wait方法报错?
VUE 绑定的方法如何直接使用外部函数?
vue2固定定位该怎么做?
谁有redis实现信号量的代码,希望借鉴一下?