[Image-SIG] Creating a grayscale ramp

Douglas Bagnall douglas at paradise.net.nz
Mon Jan 22 20:57:10 CET 2007


Cochran, Travis wrote:
> I'm trying to use the PIL to create a grayscale ramp, dark to light. I
> am able to generate an image but it is solid black. Am I using
> frombuffer wrong? Here is my code.
> 
> from PIL import Image
> 
> #Creates the list of codes from 0 to 255
> data = range(256) 
> #Creates an image out of those codes
> im = Image.frombuffer("L", (256, 1), str(data), "raw", "L", 0, 1)
                                       ^^^^^^^^^
str(data) turns the list into a 1170 byte string representation of the
list, beginning "[0, 1, 2,".  Translated back to byte values, this is
[91, 48, 44, 32, 49, 44, 32, 50, 44, 32], not [0, 1, 2].  Your "solid
black" is actually a dappled dark grey.

What you want is a 256 byte string of ascending values, which would
begin (in python's string notation) "\x00\x01\x02".  One way to get this
would be:

# you can leave out the square brackets for python 2.4 +
data = ''.join([chr(x) for x in range(256)])

im = Image.frombuffer("L", (256, 1), data, "raw", "L", 0, 1)


Note, here:
> #Resizes the image to make it easy to view
> im = im.resize((256, 768)).show()

you are setting im to None, because that is what .show() returns.  You
probably don't mean this, and would be better using two lines:

im = im.resize((256, 768))
im.show()




douglas




More information about the Image-SIG mailing list