Converting a PIL image object to a buffer

Simon Hibbs simon.hibbs at gmail.com
Thu Apr 2 17:19:44 EDT 2009


On 2 Apr, 08:28, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> 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.

Yes I did try this, the code to dump the sting version to the
clipboard worked, but pasting it back out wasn't possible although I
could print them to the console.

I don't mean wasting memory, just that actualy hitting the file system
and creating a file seems as though it shouldn't be necessery. Is
there any good reason why you can't just create an empty buffer object
or file object directly? It seems like an unecessery restriction,
unless there's some underlying reason such as that it's hard to
implement in c, which seems implausible. Sorry, that's a rhetorical
question.

I've not had a chance to work on this today, if I find an elegant way
round it I'll post the results for future googling.

Simon Hibbs



More information about the Python-list mailing list