Converting a PIL image object to a buffer

Diez B. Roggisch deets at nospam.web.de
Thu Apr 2 03:28:21 EDT 2009


Simon Hibbs schrieb:
> On 1 Apr, 21:43, Gary Herron <gher... at islandtraining.com> wrote:
>> Simon Hibbs wrote:
>>> I'm trying to dump a snapshot of my application window to the
>>> clipboard. I can use ImageGrab in PIL to get the screen data into a
>>> PIL image object, which i have converted to a bitmap using ImageWin,
>>> but when I try to pass this to the clipboard using -
>>> win32clipboard.SetClipboardData(win32clipboard.CF_BITMAP, img)
>>> It fails, telling be that "The object must support the buffer
>>> interface".
>>> How can I convert a PIL image into a buffer object? I can't find any
>>> clues.
>> PIL images have a tostring method that returns a string containing all
>> the pixel data.  Would that help you to either create the needed
>> buffer?  Or perhaps you could by-pass the need for a buffer, and just
>> use the byte string.
> 
> If I use tostring I get a string which I can put on the clipboard, but
> it isn't any kind of image. I can make a PIL image from the string but
> them I'm back to square one again.

Did you actually try that? Strings support the buffer interface, and the 
type of the binary data you set should be defined by the first argument.

Alternatively (if the string is not of the proper format), maybe storing 
the image to a (c)StringIO-object as BMP and retrieving it's value would 
help.

However, I think your concerns about "wasting memory" when using a file 
are moot - creating an extra memory buffer isn't less memory consuming, 
and if the file is living only a few seconds it might not even actually 
hit the disk at all. In the end, the important thing is the working 
clipboard.

Diez



More information about the Python-list mailing list