【问题标题】:convert pil gif image to pygame surface without saving it on the disk将 pil gif 图像转换为 pygame 表面而不将其保存在磁盘上
【发布时间】:2017-10-21 21:29:03
【问题描述】:

我想从服务器端获取图像并通过 pygame 在客户端显示它们,而不是将每个帧保存在磁盘上。使用 base64 编码和解码传输图像。当从另一端接收到数据时,它被解码为 PIL 图像。然后我可以成功地将它保存到一个临时文件中,用 pygame 打开它并显示它。但是我想直接使用 image.tostring() 来做,但注意到显示我还注意到,当我保存到临时文件图片属性是: 表面(32x32x32 SW)

当我直接这样做时: 表面(32x32x8 SW)

谢谢:

import base64
from io import BytesIO

import pygame
from PIL import  Image


def gif__to_string(filePath):
    gif_file = filePath
    content = base64.encodestring(open(gif_file, 'rb').read())

    return content


def string_to_gif(imageStr):
    gif_image = Image.open(BytesIO(base64.b64decode(imageStr)))

    return gif_image


def show_gif_working(im):
    black = (0, 0, 0)
    white = (255, 255, 255)
    pygame.init()
    width = 350;
    height = 400
    imageX = 200;  # x coordnate of image
    imageY = 30;  #
    screen = pygame.display.set_mode((width, height))
    screen.fill(black)
    im.save('temp.gif')

    surface = pygame.image.load("temp.gif").convert()

    screen.blit(surface, (imageY, imageY))
    pygame.display.flip()


def show_gif_not_working(im):
    black = (0, 0, 0)
    white = (255, 255, 255)
    pygame.init()
    width = 350;
    height = 400
    imageX = 200;  # x coordnate of image
    imageY = 30;  #
    screen = pygame.display.set_mode((width, height))
    screen.fill(black)

    mode = im.mode
    size = im.size
    data = im.tostring()

    surface1 = pygame.image.fromstring(data, size, mode)

    screen.blit(surface1, (imageX, imageY))

    pygame.display.flip()


def main():
    content = gif__to_string('face5.gif')

    print content
    myImage = string_to_gif(content)
    # show_gif_working(myImage)
    show_gif_not_working(myImage)


main()

【问题讨论】:

标签: python-2.7 pygame python-imaging-library gif


【解决方案1】:

您是否尝试过将 pygame.image.load[1] 与类似文件的对象而不是字符串一起使用?

您可以传递 StringIO[2] 对象而不是文件。

【讨论】:

  • surface = pygame.image.load1(im).convert() 出现错误
  • surface = pygame.image.load1(im).convert() AttributeError: 'module' object has no attribute 'load1'
  • 您看到的 1 和 2 只是文档的链接。如果单击您将看到的链接,则可以调用 load 传递文件对象而不是文件的路径。如果您使用图像的内容构建一个 StringIO 并将其传递给加载它应该可以工作。
【解决方案2】:

我也有同样的问题!

此线程顶部的代码适用于 jpg 文件,但现在适用于 gif。

简单的想法:

myimage = Image.open("test.gif")
pyimage = pygame.image.load(myimage)

抛出一个错误:

Traceback (most recent call last):
  File "example.py", line 12, in  <module>
    pyimage = pygame.image.load(myimage)
TypeError: not a file object

【讨论】:

  • 这并不能真正回答问题。如果您有其他问题,可以点击 进行提问。要在此问题有新答案时收到通知,您可以follow this question。一旦你有足够的reputation,你也可以add a bounty 来引起对这个问题的更多关注。 - From Review
猜你喜欢
  • 2016-12-04
  • 1970-01-01
  • 2016-05-29
  • 2014-11-08
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
相关资源
最近更新 更多