Ammi
Ammi

Reputation: 15

Python:How can I get screenshot data in PIL.ImageGrab?

I can grab a screenshot through ImageGrab.grab() in PIL,it returns an instance,but as we know,we can't send or recv an instance via socket.How to get the binary data of screenshot?

if I use save method at first,then use open(file,'wb') then I can get the binary data,but it will cost a lot of disk resources if I grab 24 pictures per second.How can I get binary data directly instead of use save and open?

while True:
    screen=ImageGrab.grab()
    screen.save('c:\\1.jpeg','jpeg')
    f=open('c:\\1.jpeg','wb')
    data=f.read()
    f.close()
    sock.sendto(data,addr)

Upvotes: 0

Views: 1124

Answers (1)

kxr
kxr

Reputation: 5548

You can e.g. serialize the image into a StringIO (in-memory file) like

mem_file = cStringIO.StringIO()
screen.save(mem_file, 'jpeg')
data = mem_file.getvalue()

.. and later open it like:

my_img = PIL.Image.open(cStringIO.StringIO(data))

Or use low-level functions like screen.tostring() / .fromstring() - plus transfer the geometry/mode extra.

Upvotes: 3

Related Questions