Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PIL Image.tostring()

I'm new to Python and PIL. I am trying to follow code samples on how to load an image into to Python through PIL and then draw its pixels using openGL. Here are some line of the code:

from Image import *
im = open("gloves200.bmp") 
pBits = im.convert('RGBA').tostring()

.....

glDrawPixels(200, 200, GL_RGBA, GL_UNSIGNED_BYTE, pBits)

This will draw a 200 x 200 patch of pixels on the canvas. However, it is not the intended image-- it looks like it is drawing pixels from random memory. The random memory hypothesis is supported by the fact that I get the same pattern even when I attempt to draw entirely different images.Can someone help me? I'm using Python 2.7 and the 2.7 version of pyopenGL and PIL on Windows XP.

screen shot

like image 232
ahoffer Avatar asked Dec 28 '22 17:12

ahoffer


1 Answers

I think you were close. Try:

pBits = im.convert("RGBA").tostring("raw", "RGBA")

The image first has to be converted to RGBA mode in order for the RGBA rawmode packer to be available (see Pack.c in libimaging). You can check that len(pBits) == im.size[0]*im.size[1]*4, which is 200x200x4 = 160,000 bytes for your gloves200 image.

like image 172
Eryk Sun Avatar answered Jan 11 '23 07:01

Eryk Sun