[Image-SIG] Colorize Image

Espen Moe-Nilssen espen at medialog.no
Wed Feb 10 12:01:24 CET 2010


Hi

We are making an open source project, http://plone.org/products/subskins
I have been trying over and over again to find a way to let PIL  
colorize an image.

It should work like this:
1) I have a greyscale image
2) A color is selected, for example "#123456"
3) The image is colorized in this way:
     Whatever was white is still white
     Whatever was black (100%) is now "#123456"
     Whaterver was grey (50%) is now 50% of "#123456"

I have tried a lot of different approaches, but the colors always  
come out too dark. Is there a way to do this ?

The code is here:
http://svn.plone.org/svn/collective/Products.PloneSubSkins/trunk/ 
Products.PloneSubSkins/Products/PloneSubSkins/browser/views.py

where the lines about this are:

______________________________________


class ColorizedImage(BrowserView):
     def __call__(self):
         portal_skins = getToolByName(self.context, 'portal_skins')
         img = portal_skins.restrictedTraverse(self.request.img)
         input = StringIO()
         input.write(img._data)
         input.seek(0)
         image = Image.open(input)
         newimage = colorize(image, self.request.color)
         output = StringIO()
         newimage.save(output, format='PNG')
         self.request.response.setHeader('Content-Type','image/png')
         return output.getvalue()

def colorize(image, color):
     color = color[1:]
     assert len(color) == 6 or len(color)==3
     if len(color)==6:
         r,g,b = int(color[:2],16),int(color[2:4],16),int(color[4:7],16)
     elif len(color)==3:
         r,g,b = int(color[0],16)*16,int(color[1],16)*16,int(color[2], 
16)*16
     palette = make_linear_ramp((r,g,b))
     if image.mode != "L":
         image = image.convert('L')
     image.putpalette(palette)
     return image

#Thanks to http://effbot.org/zone/pil-sepia.htm for the snippet
def make_linear_ramp(white):
     # putpalette expects [r,g,b,r,g,b,...]
     ramp = []
     r, g, b = white
     for i in range(255):
         ramp.extend((r*i/255, g*i/255, b*i/255))
     return ramp

__________________________________________


Espen










-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/image-sig/attachments/20100210/e83e7a1d/attachment-0001.htm>


More information about the Image-SIG mailing list