pyton Pillow 把透明背景转成白色背景的方法替换指定背景图片

起先在百度上搜到的文章,的确可以做到透明背景转成白色背景,但是缺陷非常严重,会导致图的背景产生很多像素点,而且效率也不是很高。

又经过了一番搜索之后,发现了一个更好的办法

复制代码
from PIL import Image

try:
    imagePtah = 'your image file path'
    img = Image.open(imagePtah)
    if img.mode != 'RGBA':
        image = img.convert('RGBA')
    width = img.width
    height = img.height

    image = Image.new('RGB', size=(width, height), color=(255, 255, 255))
    image.paste(img, (0, 0), mask=img)

    image.show()
    
except Exception as e:
    print(e)
复制代码

 

 

背景图替换指定图片  bk.png

复制代码
    imagePtah = '/tmp/123.png'
    img = Image.open(imagePtah)
    if img.mode != 'RGBA':
        image = img.convert('RGBA')

    width = img.width
    height = img.height

    #image = Image.new('RGB', size=(width, height), color=(255, 255, 0)) # 指定背景色
    image = Image.open("/tmp/bk.png") # 指定背景图片
    image = image.resize((width, height))

    image.paste(img, (0, 0), mask=img)

    max_pix = 512
    if max(width,height) >max_pix:
        scale = max_pix / max(width,height)
        width,height = int(width*scale),int(height*scale)
    image = image.resize((width, height))

    image.save("/tmp/4561.jpg")
复制代码

 

posted on   星河赵  阅读(662)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2020-04-24 mongoengine 中高级用户执行聚合函数等
2020-04-24 mongoDB中聚合(aggregate)的具体使用

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示