Base 64编码来自WX Python的Bitmap

时间:2015-01-13 20:38:38

标签: python bitmap wxpython base64

我正在尝试通过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()

如何从位图b

中获取字符串中的Base 64代码

修改

我也尝试过:

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.

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

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