Scale images with PIL preserving transparency and color?

前端 未结 4 1713
花落未央
花落未央 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条回答
  •  心在旅途
    2021-02-08 07:52

    It appears that PIL doesn't do alpha pre-multiplication before resizing, which is necessary to get the proper results. Fortunately it's easy to do by brute force. You must then do the reverse to the resized result.

    def premultiply(im):
        pixels = im.load()
        for y in range(im.size[1]):
            for x in range(im.size[0]):
                r, g, b, a = pixels[x, y]
                if a != 255:
                    r = r * a // 255
                    g = g * a // 255
                    b = b * a // 255
                    pixels[x, y] = (r, g, b, a)
    
    def unmultiply(im):
        pixels = im.load()
        for y in range(im.size[1]):
            for x in range(im.size[0]):
                r, g, b, a = pixels[x, y]
                if a != 255 and a != 0:
                    r = 255 if r >= a else 255 * r // a
                    g = 255 if g >= a else 255 * g // a
                    b = 255 if b >= a else 255 * b // a
                    pixels[x, y] = (r, g, b, a)
    

    Result: result of premultiply, resize, unmultiply

提交回复
热议问题