creating color gradients using PIL

Simon Hibbs simon.hibbs at gmail.com
Fri Nov 23 14:00:37 EST 2007


On 21 Nov, 06:30, Ramdas <ram... at gmail.com> wrote:
> Any ideas how we can create a color gradient using Python Imaging
> Library. Has any got some sample code that can give me some idea. I
> need to create a horizontal and vertical color gradient for a college
> project
>
> Thanks

I use these functions for building PIL images from numpy arrays

# Convert a 2-d array with typecode 'b' to an image with mode 'P'
def numpy2pil(arr):
	rows = arr.shape[0]
	cols = arr.shape[1]
	m = arr.tostring()
	out = Image.new('L', (cols, rows), 999 )
	#out.fromstring(m)
	out.fromstring(m, 'raw', 'L', 0, -1)
	return out

def pil2numpy(im, typecode='b'):
        # tostring does something funny with '1' images (packs em
tight).
        # For 'P' images, the image data is not pased through the
palette.
        if im.mode != 'L' and im.mode != 'P':
                print 'im.mode must be "L" or "P"'
                raise 'terminate'
        xsize = im.size[0]
        ysize = im.size[1]
        m = im.tostring()
        t = fromstring(m, 'b')
        tt = asarray(t, typecode)
        # Note that ysize is first:
        return reshape(tt, (ysize, xsize))

im = numpy2pil(myarray)
im.putpalette(palette_list)
im.save('myimage.png')

You'll need to import numpy and Image. You'll need to generate the
palette (juust a list) and image array (a numpy array) of course.

Simon Hibbs



More information about the Python-list mailing list