【问题标题】:How to create a pySDL2 image from a memory buffer如何从内存缓冲区创建 pySDL2 图像
【发布时间】:2022-05-12 02:17:56
【问题描述】:

我有一个 pySimpleGUI 程序,它从包含 JPEG 图像的内存缓冲区创建图像。

from PIL import ImageTk
image = ImageTk.PhotoImage( data=buf) # PhotoImage will detect a JPEG format
self.win["-IMAGE-'].update( data=image)

我想将我的应用程序转换为 pySDL2。
由于 pySimpleGUI 和 pySDL 都基于 PIL,我期待一个简单的转换,但我找不到从缓冲区创建 SDL 图像的方法。

有办法吗?

【问题讨论】:

  • PySimpleGUI 不是基于 PIL,因为 PIL 不是 Python 中的内置库。

标签: python-3.x pysimplegui pysdl2


【解决方案1】:

不确定这是否有效并且未经测试,但可能会让您走上正确的道路。如果您想了解本次访问背后的更多细节https://rubato.app/。 Image 类的完整源代码在那里。

@staticmethod
def from_surface(surface: sdl2.surface.SDL_Surface) -> "Image":
    """
    Creates an image from an SDL surface.

    Args:
        surface: the surface to create the image from.

    Returns:
        The created image.
    """
    # untested
    image = Image()
    image.image = surface
    return image

@staticmethod
def from_buffer(buffer: bytes) -> "Image":
    """
    Creates an image from a buffer.

    Args:
        buffer: bytes containing the image data.

    Returns:
        The image created from the buffer.
    """
    # untested
    rw = sdl2.SDL_RWFromMem(buffer, len(buffer))
    surface_temp = sdl2.sdlimage.IMG_Load_RW(rw, 1)

    if surface_temp is None:
        raise Exception(sdl2.sdlimage.IMG_GetError())

    surface = sdl2.SDL_ConvertSurfaceFormat(surface_temp, sdl2.SDL_PIXELFORMAT_RGBA8888, 0).contents
    sdl2.SDL_FreeSurface(surface_temp)

    return Image.from_SDL_Surface(surface)

【讨论】:

    猜你喜欢
    • 2011-06-03
    • 2012-05-14
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    相关资源
    最近更新 更多