Fastest way to tint an image with PIL

Peter Otten __peter__ at web.de
Fri Nov 7 03:15:18 EST 2008


Dan Moskowitz wrote:

> I'm using PIL to tint and composite images together.  Here's how I'm
> currently tinting images, it's really slow and I know there's got to
> be a better way:
> 
> def TintImage( im, tintColor ):
>       tint = (tintColor[0]/255.0, tintColor[1]/255.0, tintColor[2]/255.0,
> tintColor[3]/255.0)
>       pix = im.load()
>       for x in xrange( im.size[0] ):
>               for y in xrange( im.size[1] ):
>                       c = pix[x,y]
>                       pix[x,y] = (int(c[0]*tint[0]), int(c[1]*tint[1]),
> int(c[2]*tint[2]), c[3])
> 
> I thought maybe there's a way to do it using the transform method, but
> I haven't figure it out yet.  Anyone?

Too lazy to read the manual? How about

def tint_image(im, color):
    color_map = []
    for component in color:
        color_map.extend(int(component/255.0*i) for i in range(256))
    return im.point(color_map)

Peter



More information about the Python-list mailing list