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.sizescaled_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) // 2center_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"。