Python PIL Image.tostring()

北战南征 提交于 2019-12-05 16:36:35

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.

Have you tried using the conversion inside the tostring function directly?

im = open("test.bmp")
imdata = im.tostring("raw", "RGBA", 0, -1)
w, h = im.size[0], im.size[1]
glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, imdata)

Alternatively use compatibility version:

 try:
      data = im.tostring("raw", "BGRA")
 except SystemError:
      # workaround for earlier versions
      r, g, b, a = im.split()
      im = Image.merge("RGBA", (b, g, r, a))

Thank you for the help. Thanks to mikebabcock for updating the sample code on the Web. Thanks to eryksun for the code snippet-- I used it in my code.

I did find my error and it was Python newb mistake. Ouch. I declared some variables outside the scope of any function in the module and naively thought I was modifying their values inside a function. Of course, that doesn't work and so my glDrawPixels call was in fact drawing random memory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!