【问题标题】:Pygame: Send image over the network PodSixNetPygame:通过网络 PodSixNet 发送图像
【发布时间】:2019-03-09 03:49:05
【问题描述】:

我正在尝试使用 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])

有什么办法吗?

【问题讨论】:

    标签: python image networking pygame


    【解决方案1】:

    我不熟悉 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
    

    【讨论】:

    • 感谢您的回答,@Kingsley 完美运行!还必须通过服务器发送图像的大小:)
    • 不用担心,很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多