来自 WX 的 Base 64 编码位图 Python

Base 64 encode Bitmap from WX Python

我正在尝试通过 Python Wx 通过网络发送屏幕截图。我可以截屏并将其保存到文件系统,但我不想保存它。我想获取Base 64编码,不保存直接发送

这是我目前的尝试:

#!/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()

如何从位图中获取字符串中的 Base 64 代码 b

编辑

我也试过:

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

得到这个:

  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

编辑 2

试过这个:

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

这次有所不同:

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.

你可以试试这个:

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