# How to draw image in memory manually in pyglet?

In pyglet, I want to create an image buffer in memory, then set the bytes manually, then draw it. I tried making a 3x3 red square like this in my draw() function:

imageData = pyglet.image.ImageData(3, 3, 'RGB', [1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0 ])
imageData.blit(10, 10)


...but at runtime, Python complains:

ctypes.ArgumentError: argument 9: <type 'exceptions.TypeError'>: wrong type


Is this the right approach? Am I missing a step? How can I fix this?

• Are you sure the error corresponds with the code you have posted above? I do not know python but I don't see anything you have posted above with 9 arguments. AFAIK it looks like one of your arguments are not using the correct type. – Grey May 21 '13 at 23:53
• I agree with Code Assassin. The error seems to have to do with what you typed, wrong arguments? – LiquidFeline May 22 '13 at 0:16
• Well, I guess I am just assuming it is the problem as the error doesn't show up if I comment those lines... pastebin.com/iveDhYcB is the full source – Mossen May 22 '13 at 0:38

Yes, you can do this, but as the error tells you, you must use ctypes instead of Python types for it.

RGB values are unsigned byte triplets, which means c_ubyte in ctypes, also available in pyglet.gl as GL_ubyte. So you can do this:

pixels = [
255, 0, 0,      0, 255, 0,      0, 0, 255,     # RGB values range from
255, 0, 0,      255, 0, 0,      255, 0, 0,     # 0 to 255 for each color
255, 0, 0,      255, 0, 0,      255, 0, 0,     # component.
]
rawData = (GLubyte * len(pixels))(*pixels)
imageData = pyglet.image.ImageData(3, 3, 'RGB', rawData)


The above is the recommended ctypes syntax, which generates an array of GLubyte with the right size and then populates it with your pixel data.

• I've changed your colors a little from all red to illustrate the pixel order on rendering. – Ingmar Hupp Nov 12 '13 at 20:51