[Image-SIG] unable to make PIL work with cairo

Joao S. O. Bueno gwidion at mpc.com.br
Sun Jan 9 16:35:50 CET 2011


Hi Wecing --

I tried part of yoru code around and nailed the problem down:
Although the "tostring" parameter accepts a "mode" argument, as it is
documented, this mode cannot be different from teh actual current
image mode. (Or at least, it can' t be RGBA if the current image is in
RGB mode - I haven't actually tried with other combinations).

The solution for your code is therefore to convert the image to RGBA
in PIL before exporting it to a string:

>>>         img.save('%d.jpg' % self.cnt, 'JPEG') # debug! :-P
>>>
>>> +++  int_img = img.convert("RGBA")
>>>
>>>         imgd = int_img.tostring('raw', 'RGBA', 0, 1)

Regards,

   js
  -><-

On Sun, Jan 9, 2011 at 8:37 AM, wecing <w3cing at gmail.com> wrote:
> I wrote my code like this:
>>>
>>>     def video_observer(self, f):
>>>
>>>         img = Image.frombuffer('RGB', (self._width, self._height),
>>> f.data, \
>>>
>>>                                'raw', 'RGB', 0, 1)
>>>
>>>         img = img.resize((self.nwidth, self.nheight))
>>>
>>>         img.save('%d.jpg' % self.cnt, 'JPEG') # debug! :-P
>>>
>>>
>>>
>>>         imgd = img.tostring('raw', 'RGBA', 0, 1)
>>>
>>>         a = array.array('B', imgd)
>>>
>>>         surface = cairo.ImageSurface.create_for_data(a,
>>> cairo.FORMAT_ARGB32, \
>>>
>>>             self.nwidth, self.nheight, self.nwidth * 4) # self.nwidth * 4
>>>
>>>         surface.write_to_png('%d.png' % self.cnt)
>>>
>>>         self.context.set_source_surface(surface, 0, 0)
>>>
>>>         self.context.paint()
>
>
> Output of img.save() is perfectly correct, but...
>>
>>   File "main.py", line 98, in video_observer
>>
>>     imgd = img.tostring('raw', 'RGBA', 0, 1)
>>
>>   File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 535, in
>> tostring
>>
>>     e = _getencoder(self.mode, encoder_name, args)
>>
>>   File "/usr/lib/python2.6/dist-packages/PIL/Image.py", line 399, in
>> _getencoder
>>
>>     return apply(encoder, (mode,) + args + extra)
>>
>> SystemError: unknown raw mode
>
> Why?
> _______________________________________________
> Image-SIG maillist  -  Image-SIG at python.org
> http://mail.python.org/mailman/listinfo/image-sig
>
>


More information about the Image-SIG mailing list