Looking for some kind of simple tool or process for Windows that will let me convert one or more standard PNGs to premultiplied alpha.
Command line tools are ideal; I have easy access to PIL (Python Imaging Library) and Imagemagick, but will install another tool if it makes life easier.
Thanks!
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)
来源:https://stackoverflow.com/questions/6591361/method-for-converting-pngs-to-premultiplied-alpha