'How to create a pySDL2 image from a memory buffer

I have a pySimpleGUI program that create an image from a memory buffer containing a JPEG image.

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

I want to convert my application to pySDL2.
Since pySimpleGUI and pySDL are both based on PIL, I was expecting an easy conversion but I can't find a way to create a SDL image from a buffer.

Is there a way?



Solution 1:[1]

Not sure this works and is untested but might bring you down the right track. If you want more of the nitty-gritty behind this visit https://rubato.app/. The full source code of the Image class is there.

@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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yamm Elnekave