簡體   English   中英

Pygame:通過網絡發送圖像PodSixNet

[英]Pygame: Send image over the network PodSixNet

我正在嘗試使用PodSixNet通過網絡發送圖像。 我是怎么做的:

客戶端:

    #...
    image = pygame.image.load("character.png")
    img = pygame.image.tostring(image, "RGBA")
    connection.Send({"action":"setPlayerCharacter", 'playerName': self.playerName, 'playerImage': img})

服務器端:

  def Network_setPlayerCharacter(self, data):
    self.playerName = data['playerName']

    img = data['playerImage']
    self.playerImage = pygame.image.fromstring(img, (50, 50), "RGBA")
    self._server.SendPlayers() # Send data to other players

但是PodSixNet不喜歡字節。 收到此錯誤:

error: uncaptured python exception, closing channel <__main__.ClientChannel 127.0.0.1:54822 at 0x3925ef0> (<class 'UnicodeDecodeError'>:'utf-8' codec can't decode byte 0xff in position 1611: invalid start byte [C:\Users\Mikal\AppData\Local\Programs\Python\Python37-32\lib\asyncore.py|read|83] [C:\Users\Mikal\AppData\Local\Programs\Python\Python37-32\lib\asyncore.py|handle_read_event|422] [C:\Users\Mikal\AppData\Local\Programs\Python\Python37-32\lib\asynchat.py|handle_read|171] [C:\Users\Mikal\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PodSixNet\Channel.py|found_terminator|21] [C:\Users\Mikal\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PodSixNet\rencode.py|loads|333] [C:\Users\Mikal\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PodSixNet\rencode.py|f|320] [C:\Users\Mikal\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PodSixNet\rencode.py|decode_string|196])

可以解決嗎?

我不熟悉PodSixNet,但是解決這個問題的一種簡單方法似乎是對二進制圖像數據進行Base64編碼。

import base64
...

image       = pygame.image.load( "tiny_alien.png" )
image_bytes = pygame.image.tostring( image, "RGBA" )
image_str   = base64.b64encode( image_bytes ).decode('iso-8859-1') # ASCII(ish)

無論出於何種原因,base64模塊都會返回類似字節的對象, 而不是字符串,因此需要對其進行進一步解碼。

請注意,如果使用base64.a85encode(...)則生成的字符串將大大減小。

另一方面,使用base64.b64decode(...)將字符串再次恢復為二進制:

image_bytes = base64.b64decode( image_str ) # back to pygame.tostring() format

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM