Scale images with PIL preserving transparency and color?

前端 未结 4 1718
花落未央
花落未央 2021-02-08 07:27

Say you want to scale a transparent image but do not yet know the color(s) of the background you will composite it onto later. Unfortunately PIL seems to incorporate the color v

4条回答
  •  -上瘾入骨i
    2021-02-08 08:06

    You can resample each band individually:

    im.load()
    bands = im.split()
    bands = [b.resize(size, Image.LINEAR) for b in bands]
    im = Image.merge('RGBA', bands)
    

    EDIT

    Maybe by avoiding high transparency values like so (need numpy)

    import numpy as np
    
    # ...
    
    im.load()
    bands = list(im.split())
    a = np.asarray(bands[-1])
    a.flags.writeable = True
    a[a != 0] = 1
    bands[-1] = Image.fromarray(a)
    bands = [b.resize(size, Image.LINEAR) for b in bands]
    a = np.asarray(bands[-1])
    a.flags.writeable = True
    a[a != 0] = 255
    bands[-1] = Image.fromarray(a)
    im = Image.merge('RGBA', bands)
    

提交回复
热议问题