I wrestled a bear once.
I wrestled a bear once.

Reputation: 23399

Base 64 encode Bitmap from WX Python

I am trying to send a screenshot over a network via Python Wx. I am able to take a screenshot and save it to the filesystem, but I do not want to save it. I want to get the Base 64 code and send it without saving.

Here is my current attempt:

#!/usr/bin/env python

import requests
import socket
import time
import wx
import base64

def checkServer():
    sesh = requests.session()
    app = wx.App(False)
    while True:
        s = wx.ScreenDC()
        w, h = s.Size.Get()
        b = wx.EmptyBitmap(w, h)
        m = wx.MemoryDCFromDC(s)
        m.SelectObject(b)
        m.Blit(0, 0, w, h, s, 0, 0)
        m.SelectObject(wx.NullBitmap)

        #outputs: <wx._gdi.Bitmap; proxy of <Swig Object of type 'wxBitmap *' at 0x2001640> >
        #print b 

        #Does NOT Work, outputs: TypeError: must be convertible to a buffer, not Bitmap
        #base64img = base64.b64encode(b) 

        # Works, but not what I want to do
        #b.SaveFile("screenshot.png", wx.BITMAP_TYPE_PNG)

        hostname = socket.gethostname()
        url = 'http://localhost/callcenter/monitor/post.php'
        payload = {
            'host' : hostname,
            #'image' : base64img
        }
        headers = {
            'Connection' : "keep-alive", 
            'Content-Type' : "application/x-www-form-urlencoded"
        }
        r = sesh.post(url, data=payload, headers=headers, allow_redirects=False, verify=False)
        content = r.text
        print content
        time.sleep(5)

checkServer()

How can I get the Base 64 code in a string from the bitmap b?

EDIT

I also tried:

buf=io.BytesIO()
b.CopyToBuffer(buf)
base64img = base64.b64encode(buf)
print base64img

and got this:

  File "./main.py", line 51, in <module>
    checkServer()
  File "./main.py", line 29, in checkServer
    b.CopyToBuffer(buf)
  File "/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode/wx/_gdi.py", line 740, in CopyToBuffer
    return _gdi_.Bitmap_CopyToBuffer(*args, **kwargs)
TypeError: expected a readable buffer object

Edit 2

Tried this:

buf=bytearray()
b.CopyToBuffer(buf)
base64img = base64.b64encode(buf)
print base64img

And got something different this time:

Traceback (most recent call last):
  File "./main.py", line 51, in <module>
    checkServer()
  File "./main.py", line 29, in checkServer
    b.CopyToBuffer(buf)
  File "/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode/wx/_gdi.py", line 740, in CopyToBuffer
    return _gdi_.Bitmap_CopyToBuffer(*args, **kwargs)
ValueError: Invalid data buffer size.

Upvotes: 1

Views: 1186

Answers (1)

Kolmar
Kolmar

Reputation: 14224

You could try this:

base64img = base64.b64encode(b.ConvertToImage().GetData())

Upvotes: 2

Related Questions