Pure Python wrapper around SDL2 libraries for cross-platform multimedia development
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Image loading, saving, and manipulation through SDL2_image integration and surface operations. PySDL2 provides comprehensive support for various image formats and pixel-level manipulation.
SDL2_image initialization and format support detection.
def IMG_Init(flags: int) -> int:
"""
Initialize IMG with specific format support.
Parameters:
- flags: combination of IMG_INIT_* flags for desired formats
Returns:
Flags indicating successfully initialized formats
"""
def IMG_Quit() -> None:
"""Shut down IMG and free resources."""
def IMG_GetError() -> bytes:
"""Get last IMG error message."""
def IMG_SetError(fmt: bytes) -> None:
"""Set IMG error message."""
# Image format initialization flags
IMG_INIT_JPG: int = 0x00000001 # JPEG support
IMG_INIT_PNG: int = 0x00000002 # PNG support
IMG_INIT_TIF: int = 0x00000004 # TIFF support
IMG_INIT_WEBP: int = 0x00000008 # WebP support
IMG_INIT_JXL: int = 0x00000010 # JPEG XL support
IMG_INIT_AVIF: int = 0x00000020 # AVIF supportFunctions for loading images from various sources.
def IMG_Load(file: bytes) -> SDL_Surface:
"""
Load image from file (format auto-detected).
Parameters:
- file: path to image file as bytes
Returns:
SDL_Surface containing image or None on failure
"""
def IMG_Load_RW(src: SDL_RWops, freesrc: int) -> SDL_Surface:
"""Load image from SDL_RWops source."""
def IMG_LoadTyped_RW(src: SDL_RWops, freesrc: int, type: bytes) -> SDL_Surface:
"""
Load image from SDL_RWops with specified format.
Parameters:
- src: SDL_RWops source
- freesrc: whether to free source after loading
- type: image format hint (b"PNG", b"JPG", etc.)
Returns:
SDL_Surface containing image or None on failure
"""
def IMG_LoadTexture(renderer: SDL_Renderer, file: bytes) -> SDL_Texture:
"""
Load image directly as texture.
Parameters:
- renderer: renderer to create texture for
- file: path to image file as bytes
Returns:
SDL_Texture containing image or None on failure
"""
def IMG_LoadTexture_RW(renderer: SDL_Renderer, src: SDL_RWops, freesrc: int) -> SDL_Texture:
"""Load image as texture from SDL_RWops source."""
def IMG_LoadTextureTyped_RW(renderer: SDL_Renderer, src: SDL_RWops, freesrc: int, type: bytes) -> SDL_Texture:
"""Load image as texture from SDL_RWops with format hint."""Functions for loading specific image formats.
def IMG_LoadBMP_RW(src: SDL_RWops) -> SDL_Surface:
"""Load BMP image from SDL_RWops."""
def IMG_LoadGIF_RW(src: SDL_RWops) -> SDL_Surface:
"""Load GIF image from SDL_RWops."""
def IMG_LoadJPG_RW(src: SDL_RWops) -> SDL_Surface:
"""Load JPEG image from SDL_RWops."""
def IMG_LoadLBM_RW(src: SDL_RWops) -> SDL_Surface:
"""Load LBM image from SDL_RWops."""
def IMG_LoadPCX_RW(src: SDL_RWops) -> SDL_Surface:
"""Load PCX image from SDL_RWops."""
def IMG_LoadPNG_RW(src: SDL_RWops) -> SDL_Surface:
"""Load PNG image from SDL_RWops."""
def IMG_LoadPNM_RW(src: SDL_RWops) -> SDL_Surface:
"""Load PNM image from SDL_RWops."""
def IMG_LoadSVG_RW(src: SDL_RWops) -> SDL_Surface:
"""Load SVG image from SDL_RWops."""
def IMG_LoadTGA_RW(src: SDL_RWops) -> SDL_Surface:
"""Load TGA image from SDL_RWops."""
def IMG_LoadTIF_RW(src: SDL_RWops) -> SDL_Surface:
"""Load TIFF image from SDL_RWops."""
def IMG_LoadWEBP_RW(src: SDL_RWops) -> SDL_Surface:
"""Load WebP image from SDL_RWops."""
def IMG_LoadXCF_RW(src: SDL_RWops) -> SDL_Surface:
"""Load XCF image from SDL_RWops."""
def IMG_LoadXPM_RW(src: SDL_RWops) -> SDL_Surface:
"""Load XPM image from SDL_RWops."""
def IMG_LoadXV_RW(src: SDL_RWops) -> SDL_Surface:
"""Load XV image from SDL_RWops."""Functions for detecting image formats.
def IMG_isBMP(src: SDL_RWops) -> int:
"""Check if source contains BMP image."""
def IMG_isGIF(src: SDL_RWops) -> int:
"""Check if source contains GIF image."""
def IMG_isJPG(src: SDL_RWops) -> int:
"""Check if source contains JPEG image."""
def IMG_isLBM(src: SDL_RWops) -> int:
"""Check if source contains LBM image."""
def IMG_isPCX(src: SDL_RWops) -> int:
"""Check if source contains PCX image."""
def IMG_isPNG(src: SDL_RWops) -> int:
"""Check if source contains PNG image."""
def IMG_isPNM(src: SDL_RWops) -> int:
"""Check if source contains PNM image."""
def IMG_isSVG(src: SDL_RWops) -> int:
"""Check if source contains SVG image."""
def IMG_isTIF(src: SDL_RWops) -> int:
"""Check if source contains TIFF image."""
def IMG_isWEBP(src: SDL_RWops) -> int:
"""Check if source contains WebP image."""
def IMG_isXCF(src: SDL_RWops) -> int:
"""Check if source contains XCF image."""
def IMG_isXPM(src: SDL_RWops) -> int:
"""Check if source contains XPM image."""
def IMG_isXV(src: SDL_RWops) -> int:
"""Check if source contains XV image."""Functions for saving images to files.
def IMG_SavePNG(surface: SDL_Surface, file: bytes) -> int:
"""
Save surface as PNG file.
Parameters:
- surface: surface to save
- file: output file path as bytes
Returns:
0 on success, -1 on failure
"""
def IMG_SavePNG_RW(surface: SDL_Surface, dst: SDL_RWops, freedst: int) -> int:
"""Save surface as PNG to SDL_RWops destination."""
def IMG_SaveJPG(surface: SDL_Surface, file: bytes, quality: int) -> int:
"""
Save surface as JPEG file.
Parameters:
- surface: surface to save
- file: output file path as bytes
- quality: JPEG quality (0-100)
Returns:
0 on success, -1 on failure
"""
def IMG_SaveJPG_RW(surface: SDL_Surface, dst: SDL_RWops, freedst: int, quality: int) -> int:
"""Save surface as JPEG to SDL_RWops destination."""Extension module functions for simplified image handling.
def get_image_formats() -> list[str]:
"""
Get list of supported image formats.
Returns:
List of supported format strings (e.g., ["PNG", "JPEG", "BMP"])
"""
def load_img(file: str) -> SDL_Surface:
"""
Load image from file (high-level wrapper).
Parameters:
- file: path to image file as string
Returns:
SDL_Surface containing image or None on failure
"""
def load_bmp(file: str) -> SDL_Surface:
"""
Load BMP image from file.
Parameters:
- file: path to BMP file as string
Returns:
SDL_Surface containing image or None on failure
"""
def save_bmp(surface: SDL_Surface, file: str) -> None:
"""
Save surface as BMP file.
Parameters:
- surface: surface to save
- file: output file path as string
"""
def load_svg(file: str, width: int = None, height: int = None) -> SDL_Surface:
"""
Load SVG image from file with optional size.
Parameters:
- file: path to SVG file as string
- width: desired width (None for original)
- height: desired height (None for original)
Returns:
SDL_Surface containing rendered SVG or None on failure
"""Functions for direct pixel manipulation on surfaces.
def pixels2d(surface: SDL_Surface) -> PixelView:
"""
Get 2D array view of surface pixels.
Parameters:
- surface: surface to access
Returns:
PixelView object for 2D pixel access
"""
def pixels3d(surface: SDL_Surface) -> PixelView:
"""
Get 3D array view of surface pixels (with RGB components).
Parameters:
- surface: surface to access
Returns:
PixelView object for 3D pixel access
"""
def surface_to_ndarray(surface: SDL_Surface, dtype: type = None) -> object:
"""
Convert surface to NumPy-like array.
Parameters:
- surface: surface to convert
- dtype: desired array data type
Returns:
Array object compatible with NumPy operations
"""
class PixelView:
"""2D/3D view of surface pixels for direct manipulation."""
def __init__(self, surface: SDL_Surface, transpose: bool = True):
"""
Create pixel view for surface.
Parameters:
- surface: surface to create view for
- transpose: whether to transpose array dimensions
"""
def __getitem__(self, key) -> int:
"""Get pixel value at coordinates."""
def __setitem__(self, key, value: int) -> None:
"""Set pixel value at coordinates."""
@property
def ndim(self) -> int:
"""Get number of dimensions."""
@property
def shape(self) -> tuple[int, ...]:
"""Get array shape."""
@property
def strides(self) -> tuple[int, ...]:
"""Get array strides."""
class SurfaceArray:
"""Array interface for surface manipulation."""
def __init__(self, surface: SDL_Surface):
"""
Create surface array.
Parameters:
- surface: surface to wrap
"""
def __array__(self) -> object:
"""Convert to array object."""Functions for transparency and color key operations.
def SDL_SetColorKey(surface: SDL_Surface, flag: int, key: int) -> int:
"""
Set color key (transparent color) for surface.
Parameters:
- surface: surface to modify
- flag: SDL_TRUE to enable, SDL_FALSE to disable
- key: color value to treat as transparent
Returns:
0 on success, -1 on failure
"""
def SDL_GetColorKey(surface: SDL_Surface, key: ctypes.POINTER(ctypes.c_uint32)) -> int:
"""Get color key for surface."""
def SDL_SetSurfaceAlphaMod(surface: SDL_Surface, alpha: int) -> int:
"""
Set surface alpha modulation (0-255).
Parameters:
- surface: surface to modify
- alpha: alpha value (0=transparent, 255=opaque)
Returns:
0 on success, -1 on failure
"""
def SDL_GetSurfaceAlphaMod(surface: SDL_Surface, alpha: ctypes.POINTER(ctypes.c_uint8)) -> int:
"""Get surface alpha modulation."""
def SDL_SetSurfaceColorMod(surface: SDL_Surface, r: int, g: int, b: int) -> int:
"""
Set surface color modulation.
Parameters:
- surface: surface to modify
- r, g, b: color modulation values (0-255 each)
Returns:
0 on success, -1 on failure
"""
def SDL_GetSurfaceColorMod(surface: SDL_Surface, r: ctypes.POINTER(ctypes.c_uint8),
g: ctypes.POINTER(ctypes.c_uint8), b: ctypes.POINTER(ctypes.c_uint8)) -> int:
"""Get surface color modulation."""
def SDL_SetSurfaceBlendMode(surface: SDL_Surface, blendMode: int) -> int:
"""Set surface blend mode."""
def SDL_GetSurfaceBlendMode(surface: SDL_Surface, blendMode: ctypes.POINTER(ctypes.c_int)) -> int:
"""Get surface blend mode."""Functions for converting between pixel formats.
def SDL_ConvertSurface(src: SDL_Surface, fmt: SDL_PixelFormat, flags: int) -> SDL_Surface:
"""
Convert surface to specified pixel format.
Parameters:
- src: source surface
- fmt: target pixel format
- flags: conversion flags
Returns:
New surface with converted format or None on failure
"""
def SDL_ConvertSurfaceFormat(src: SDL_Surface, pixel_format: int, flags: int) -> SDL_Surface:
"""
Convert surface to specified pixel format constant.
Parameters:
- src: source surface
- pixel_format: target pixel format constant
- flags: conversion flags
Returns:
New surface with converted format or None on failure
"""
def SDL_CreateRGBSurfaceWithFormat(flags: int, width: int, height: int, depth: int, format: int) -> SDL_Surface:
"""Create surface with specific pixel format."""
def SDL_CreateRGBSurfaceWithFormatFrom(pixels: ctypes.c_void_p, width: int, height: int,
depth: int, pitch: int, format: int) -> SDL_Surface:
"""Create surface from existing pixel data."""import sdl2
import sdl2.sdlimage
import sdl2.ext
# Initialize SDL2 and SDL2_image
sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
sdl2.sdlimage.IMG_Init(sdl2.sdlimage.IMG_INIT_PNG | sdl2.sdlimage.IMG_INIT_JPG)
# Create window and renderer
window = sdl2.SDL_CreateWindow(b"Image Display",
sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED,
800, 600, sdl2.SDL_WINDOW_SHOWN)
renderer = sdl2.SDL_CreateRenderer(window, -1, sdl2.SDL_RENDERER_ACCELERATED)
# Load image directly as texture
texture = sdl2.sdlimage.IMG_LoadTexture(renderer, b"image.png")
if not texture:
print(f"Failed to load image: {sdl2.sdlimage.IMG_GetError()}")
exit(1)
# Get image dimensions
w = ctypes.c_int()
h = ctypes.c_int()
sdl2.SDL_QueryTexture(texture, None, None, w, h)
# Main loop
running = True
event = sdl2.SDL_Event()
while running:
while sdl2.SDL_PollEvent(event):
if event.type == sdl2.SDL_QUIT:
running = False
# Clear screen
sdl2.SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255)
sdl2.SDL_RenderClear(renderer)
# Render image centered
dest_rect = sdl2.SDL_Rect(
(800 - w.value) // 2,
(600 - h.value) // 2,
w.value,
h.value
)
sdl2.SDL_RenderCopy(renderer, texture, None, dest_rect)
sdl2.SDL_RenderPresent(renderer)
# Cleanup
sdl2.SDL_DestroyTexture(texture)
sdl2.SDL_DestroyRenderer(renderer)
sdl2.SDL_DestroyWindow(window)
sdl2.sdlimage.IMG_Quit()
sdl2.SDL_Quit()import sdl2.ext
# Initialize SDL2 extensions (automatically initializes SDL2_image)
sdl2.ext.init()
# Create window and renderer
window = sdl2.ext.Window("Image Example", size=(800, 600))
window.show()
renderer = sdl2.ext.Renderer(window)
# Check supported formats
formats = sdl2.ext.get_image_formats()
print(f"Supported formats: {formats}")
# Load images using high-level functions
try:
# Load various formats
png_surface = sdl2.ext.load_img("image.png")
jpg_surface = sdl2.ext.load_img("photo.jpg")
bmp_surface = sdl2.ext.load_bmp("sprite.bmp")
# Convert surfaces to textures
png_texture = sdl2.ext.Texture(renderer, png_surface)
jpg_texture = sdl2.ext.Texture(renderer, jpg_surface)
bmp_texture = sdl2.ext.Texture(renderer, bmp_surface)
# Free surfaces (textures have copies)
sdl2.SDL_FreeSurface(png_surface)
sdl2.SDL_FreeSurface(jpg_surface)
sdl2.SDL_FreeSurface(bmp_surface)
# Main loop
running = True
while running:
events = sdl2.ext.get_events()
for event in events:
if event.type == sdl2.SDL_QUIT:
running = False
# Clear and render images
renderer.clear((50, 50, 50))
# Render images side by side
renderer.copy(png_texture, dstrect=sdl2.SDL_Rect(50, 50, 200, 200))
renderer.copy(jpg_texture, dstrect=sdl2.SDL_Rect(300, 50, 200, 200))
renderer.copy(bmp_texture, dstrect=sdl2.SDL_Rect(550, 50, 200, 200))
renderer.present()
except Exception as e:
print(f"Error loading images: {e}")
sdl2.ext.quit()import sdl2
import sdl2.ext
# Initialize SDL2
sdl2.ext.init()
# Create surface for pixel manipulation
surface = sdl2.SDL_CreateRGBSurface(0, 256, 256, 32, 0, 0, 0, 0)
# Get pixel view for direct access
pixel_view = sdl2.ext.pixels2d(surface)
# Create gradient pattern
for x in range(256):
for y in range(256):
# Create RGB color from coordinates
r = x
g = y
b = (x + y) // 2
# Pack RGB into pixel format (assuming 32-bit RGB)
color = (r << 16) | (g << 8) | b
pixel_view[x, y] = color
# Create window and renderer
window = sdl2.ext.Window("Pixel Manipulation", size=(512, 512))
window.show()
renderer = sdl2.ext.Renderer(window)
# Convert surface to texture
texture = sdl2.ext.Texture(renderer, surface)
# Main loop
running = True
while running:
events = sdl2.ext.get_events()
for event in events:
if event.type == sdl2.SDL_QUIT:
running = False
# Render gradient
renderer.clear((0, 0, 0))
renderer.copy(texture, dstrect=sdl2.SDL_Rect(128, 128, 256, 256))
renderer.present()
# Cleanup
sdl2.SDL_FreeSurface(surface)
sdl2.ext.quit()import sdl2
import sdl2.sdlimage
# Initialize
sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
sdl2.sdlimage.IMG_Init(sdl2.sdlimage.IMG_INIT_PNG | sdl2.sdlimage.IMG_INIT_JPG)
# Load image
surface = sdl2.sdlimage.IMG_Load(b"input.jpg")
if not surface:
print("Failed to load image")
exit(1)
print(f"Original format: {surface.contents.format.contents.BitsPerPixel} bpp")
# Convert to different pixel format (24-bit RGB)
rgb_surface = sdl2.SDL_ConvertSurfaceFormat(surface, sdl2.SDL_PIXELFORMAT_RGB24, 0)
# Save as PNG
result = sdl2.sdlimage.IMG_SavePNG(rgb_surface, b"output.png")
if result != 0:
print(f"Failed to save PNG: {sdl2.sdlimage.IMG_GetError()}")
# Save as JPEG with quality setting
result = sdl2.sdlimage.IMG_SaveJPG(rgb_surface, b"output_quality.jpg", 90)
if result != 0:
print(f"Failed to save JPEG: {sdl2.sdlimage.IMG_GetError()}")
# Save as BMP using SDL function
result = sdl2.SDL_SaveBMP(rgb_surface, b"output.bmp")
if result != 0:
print(f"Failed to save BMP: {sdl2.SDL_GetError()}")
# Cleanup
sdl2.SDL_FreeSurface(rgb_surface)
sdl2.SDL_FreeSurface(surface)
sdl2.sdlimage.IMG_Quit()
sdl2.SDL_Quit()
print("Image conversion and saving completed!")import sdl2
import sdl2.sdlimage
import sdl2.ext
# Initialize
sdl2.ext.init()
window = sdl2.ext.Window("Transparency Example", size=(800, 600))
window.show()
renderer = sdl2.ext.Renderer(window)
# Load sprite with transparent background
sprite_surface = sdl2.sdlimage.IMG_Load(b"sprite_with_magenta_bg.png")
# Set magenta (255, 0, 255) as transparent color key
magenta = sdl2.SDL_MapRGB(sprite_surface.contents.format, 255, 0, 255)
sdl2.SDL_SetColorKey(sprite_surface, sdl2.SDL_TRUE, magenta)
# Create texture from surface
sprite_texture = sdl2.ext.Texture(renderer, sprite_surface)
sdl2.SDL_FreeSurface(sprite_surface)
# Load background image
bg_surface = sdl2.sdlimage.IMG_Load(b"background.jpg")
bg_texture = sdl2.ext.Texture(renderer, bg_surface)
sdl2.SDL_FreeSurface(bg_surface)
# Main loop
sprite_x = 0
running = True
while running:
events = sdl2.ext.get_events()
for event in events:
if event.type == sdl2.SDL_QUIT:
running = False
# Move sprite across screen
sprite_x += 2
if sprite_x > 800:
sprite_x = -64
# Render background
renderer.clear((0, 0, 0))
renderer.copy(bg_texture)
# Render sprite with transparency
renderer.copy(sprite_texture, dstrect=sdl2.SDL_Rect(sprite_x, 200, 64, 64))
renderer.present()
sdl2.ext.quit()Install with Tessl CLI
npx tessl i tessl/pypi-pysdl2