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

最佳答案

您可以尝试以下方法:

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

关于python - WX Python的Base 64编码位图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27931079/

10-10 09:42
查看更多