Method for converting PNGs to premultiplied alpha [closed]

泪湿孤枕 提交于 2019-11-30 09:36:27

I just released a bit of code in Python and in C that does what you are looking for. It's on github: http://github.com/maxme/PNG-Alpha-Premultiplier

The Python version is based on the cssndrx response. C version is based on libpng.

A more complete version of the cssndrx answer, using slicing in numpy to improve speed:

import Image
import numpy

im = Image.open('myimage.png').convert('RGBA')
a = numpy.fromstring(im.tostring(), dtype=numpy.uint8)
alphaLayer = a[3::4] / 255.0
a[::4]  *= alphaLayer
a[1::4] *= alphaLayer
a[2::4] *= alphaLayer

im = Image.fromstring("RGBA", im.size, a.tostring())

Et voila !

Using ImageMagick, as requested:

convert in.png -background black -alpha Remove in.png -compose Copy_Opacity -composite out.png

Thanks @mf511 for the update.

It should be possible to do this through PIL. Here is a rough outline of the steps:

1) Load the image and convert to numpy array

    im = Image.open('myimage.png').convert('RGBA')
    matrix = numpy.array(im)

2) Modify the matrix in place. The matrix is a list of lists of the pixels within each row. Pixels are represented as [r, g, b, a]. Write your own function to convert each [r, g, b, a] pixel to the [r, g, b] value you desire.

3) Convert the matrix back to an image using

    new_im = Image.fromarray(matrix)

Using PIL only:

def premultiplyAlpha(img):
    # fake transparent image to blend with
    transparent = Image.new("RGBA", img.size, (0, 0, 0, 0))
    # blend with transparent image using own alpha
    return Image.composite(img, transparent, img)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!