pyglet.image

Submodules

Details

Image load, capture and high-level texture functions.

Only basic functionality is described here; for full reference see the accompanying documentation.

To load an image:

from pyglet import image
pic = image.load('picture.png')

The supported image file types include PNG, BMP, GIF, JPG, and many more, somewhat depending on the operating system. To load an image from a file-like object instead of a filename:

pic = image.load('hint.jpg', file=fileobj)

The hint helps the module locate an appropriate decoder to use based on the file extension. It is optional.

Once loaded, images can be used directly by most other modules of pyglet. All images have a width and height you can access:

width, height = pic.width, pic.height

You can extract a region of an image (this keeps the original image intact; the memory is shared efficiently):

subimage = pic.get_region(x, y, width, height)

Remember that y-coordinates are always increasing upwards.

Drawing images

To draw an image at some point on the screen:

pic.blit(x, y, z)

This assumes an appropriate view transform and projection have been applied.

Some images have an intrinsic “anchor point”: this is the point which will be aligned to the x and y coordinates when the image is drawn. By default, the anchor point is the lower-left corner of the image. You can use the anchor point to center an image at a given point, for example:

pic.anchor_x = pic.width // 2
pic.anchor_y = pic.height // 2
pic.blit(x, y, z)

Texture access

If you are using OpenGL directly, you can access the image as a texture:

texture = pic.get_texture()

(This is the most efficient way to obtain a texture; some images are immediately loaded as textures, whereas others go through an intermediate form). To use a texture with pyglet.gl:

from pyglet.graphics.api.gl import *
glEnable(texture.target)        # typically target is GL_TEXTURE_2D
glBindTexture(texture.target, texture.id)
# ... draw with the texture

Pixel access

To access raw pixel data of an image:

rawimage = pic.get_image_data()

(If the image has just been loaded this will be a very quick operation; however if the image is a texture a relatively expensive readback operation will occur). The pixels can be accessed as bytes:

format = 'RGBA'
pitch = rawimage.width * len(format)
pixels = rawimage.get_bytes(format, pitch)

“format” strings consist of characters that give the byte order of each color component. For example, if rawimage.format is ‘RGBA’, there are four color components: red, green, blue and alpha, in that order. Other common format strings are ‘RGB’, ‘LA’ (luminance, alpha) and ‘I’ (intensity).

The “pitch” of an image is the number of bytes in a row (this may validly be more than the number required to make up the width of the image, it is common to see this for word alignment). If “pitch” is negative the rows of the image are ordered from top to bottom, otherwise they are ordered from bottom to top.

Retrieving data with the format and pitch given in ImageData.format and ImageData.pitch avoids the need for data conversion (assuming you can make use of the data in this arbitrary format).

Classes

Data

class ImageData

Bases: _AbstractImage

An image represented as a string of unsigned bytes.

__init__(
width: int,
height: int,
fmt: str,
data: bytes,
pitch: int | None = None,
data_type: Literal['f', 'i', 'I', 'h', 'H', 'b', 'B', 'q', 'Q', '?', 'd'] = 'B',
) None

Initialize image data.

Parameters:
  • width (int) – Width of image data

  • height (int) – Height of image data

  • fmt (str) – A valid format string, such as ‘RGB’, ‘RGBA’, ‘ARGB’, etc.

  • data (bytes) – A sequence of bytes containing the raw image data.

  • pitch (int | None) – If specified, the number of bytes per row. Negative values indicate a top-to-bottom arrangement. Defaults to width * len(format).

  • data_type (Literal['f', 'i', 'I', 'h', 'H', 'b', 'B', 'q', 'Q', '?', 'd']) – The data type of the underlying data. Defaults to unsigned bytes.

blit(
x: int,
y: int,
z: int = 0,
width: int | None = None,
height: int | None = None,
) None
Return type:

None

convert(fmt: str, pitch: int) bytes

Convert data to the desired format.

This method does not alter this instance’s current format or pitch.

Can be expensive depending on the size of the image and kind of re-ordering.

Return type:

bytes

create_texture(
cls: type[GLTexture],
) GLTexture

Given a texture class, create a texture containing this image.

Return type:

GLTexture

get_bytes(fmt: str | None = None, pitch: int | None = None) bytes

Get the byte data of the image.

This method returns the raw byte data of the image, with optional conversion. To convert the data into another format, you can provide fmt and pitch arguments. For example, if the image format is RGBA, and you wish to get the byte data in RGB format:

rgb_pitch = my_image.width * len('RGB')
rgb_img_bytes = my_image.get_bytes(fmt='RGB', pitch=rgb_pitch)

The image pitch may be negative, so be sure to check that when converting to another format. Switching the sign of the pitch will cause the image to appear “upside-down”.

Parameters:
  • fmt (str | None) – If provided, get the data in another format.

  • pitch (int | None) – The number of bytes per row. This generally means the length of the format string * the number of pixels per row. Negative values indicate a top-to-bottom arrangement.

Return type:

bytes

Note

Conversion to another format is done on the CPU, and can be somewhat costly for larger images. Consider performing conversion at load time for framerate sensitive applictions.

get_image_data() ImageData

Get an ImageData view of this image.

Changes to the returned instance may or may not be reflected in this image.

Return type:

ImageData

get_region(
x: int,
y: int,
width: int,
height: int,
) ImageDataRegion

Retrieve a rectangular region of this image data.

Return type:

ImageDataRegion

get_texture() GLTexture
Return type:

GLTexture

set_bytes(fmt: str, pitch: int, data: bytes) None

Set the byte data of the image.

Parameters:
  • fmt (str) – The format string of the supplied data. For example: “RGB” or “RGBA”

  • pitch (int) – The number of bytes per row. This generally means the length of the format string * the number of pixels per row. Negative values indicate a top-to-bottom arrangement.

  • data (bytes) – Image data as bytes.

Return type:

None

property data_type: str
property format: str

Format string of the data. Read-write.

class ImageDataRegion

Bases: ImageData

A region of image data taken from an existing ImageData or region.

__init__(
x: int,
y: int,
width: int,
height: int,
image_data: ImageData,
) None

Initialize image data.

Parameters:
  • width (int) – Width of image data

  • height (int) – Height of image data

  • fmt – A valid format string, such as ‘RGB’, ‘RGBA’, ‘ARGB’, etc.

  • data – A sequence of bytes containing the raw image data.

  • pitch – If specified, the number of bytes per row. Negative values indicate a top-to-bottom arrangement. Defaults to width * len(format).

  • data_type – The data type of the underlying data. Defaults to unsigned bytes.

get_bytes(fmt: str | None = None, pitch: int | None = None) bytes

Get the byte data of the image.

This method returns the raw byte data of the image, with optional conversion. To convert the data into another format, you can provide fmt and pitch arguments. For example, if the image format is RGBA, and you wish to get the byte data in RGB format:

rgb_pitch = my_image.width * len('RGB')
rgb_img_bytes = my_image.get_bytes(fmt='RGB', pitch=rgb_pitch)

The image pitch may be negative, so be sure to check that when converting to another format. Switching the sign of the pitch will cause the image to appear “upside-down”.

Parameters:
  • fmt (str | None) – If provided, get the data in another format.

  • pitch (int | None) – The number of bytes per row. This generally means the length of the format string * the number of pixels per row. Negative values indicate a top-to-bottom arrangement.

Return type:

bytes

Note

Conversion to another format is done on the CPU, and can be somewhat costly for larger images. Consider performing conversion at load time for framerate sensitive applictions.

get_region(
x: int,
y: int,
width: int,
height: int,
) ImageDataRegion

Retrieve a rectangular region of this image data.

Return type:

ImageDataRegion

set_bytes(fmt: str, pitch: int, data: bytes) None

Set the byte data of the image.

Parameters:
  • fmt (str) – The format string of the supplied data. For example: “RGB” or “RGBA”

  • pitch (int) – The number of bytes per row. This generally means the length of the format string * the number of pixels per row. Negative values indicate a top-to-bottom arrangement.

  • data (bytes) – Image data as bytes.

Return type:

None

class CompressedImageData

Bases: _AbstractImage

Compressed image data suitable for direct uploading to GPU.

__init__(
width: int,
height: int,
fmt: CompressionFormat,
data: bytes,
extension: str | None = None,
decoder: Callable[[bytes, int, int], _AbstractImage] | None = None,
) None

Construct a CompressedImageData with the given compressed data.

Parameters:
  • width (int) – The width of the image.

  • height (int) – The height of the image.

  • data (bytes) – An array of bytes containing the compressed image data.

  • extension (str | None) – If specified, gives the name of the extension to check for before creating a texture.

  • decoder (Callable[[bytes, int, int], _AbstractImage] | None) – An optional fallback function used to decode the compressed data. This function is called if the required extension is not present.

blit(x: int, y: int, z: int = 0) None
Return type:

None

create_texture(
cls: type[GLCompressedTexture],
) GLTexture

Given a texture class, create a texture containing this image.

Return type:

GLTexture

get_image_data() CompressedImageData

Get an ImageData view of this image.

Changes to the returned instance may or may not be reflected in this image.

Return type:

CompressedImageData

get_region(
x: int,
y: int,
width: int,
height: int,
) _AbstractImage

Retrieve a rectangular region of this image.

Return type:

_AbstractImage

get_texture() GLCompressedTexture
Return type:

GLCompressedTexture

set_mipmap_data(level: int, data: bytes) None

Set compressed image data for a mipmap level.

Supplied data gives a compressed image for the given mipmap level. This image data must be in the same format as was used in the constructor. The image data must also be of the correct dimensions for the level (i.e., width >> level, height >> level); but this is not checked. If any mipmap levels are specified, they are used; otherwise, mipmaps for mipmapped_texture are generated automatically.

Return type:

None

Image Sequences

class ImageGrid

An imaginary grid placed over an image allowing easy access to regular regions of that image.

The grid can be accessed either as a complete image, or as a sequence of images.

Any TextureGrid generated via the method below will create a separate texture resource:

image_grid = ImageGrid(...)
texture_grid = image_grid.get_texture_sequence()

For existing Texture’s, it is recommended to use TextureGrid directly.

__init__(
image: ImageData | ImageDataRegion,
rows: int,
columns: int,
item_width: int | None = None,
item_height: int | None = None,
row_padding: int = 0,
column_padding: int = 0,
) None

Construct a grid for the given image.

You can specify parameters for the grid, for example setting the padding between cells. Grids are always aligned to the bottom-left corner of the image.

Parameters:
  • image (ImageData | ImageDataRegion) – Image over which to construct the grid.

  • rows (int) – Number of rows in the grid.

  • columns (int) – Number of columns in the grid.

  • item_width (int | None) – Width of each column. If unspecified, is calculated such that the entire image width is used.

  • item_height (int | None) – Height of each row. If unspecified, is calculated such that the entire image height is used.

  • row_padding (int) – Pixels separating adjacent rows. The padding is only inserted between rows, not at the edges of the grid.

  • column_padding (int) – Pixels separating adjacent columns. The padding is only inserted between columns, not at the edges of the grid.

get_image_data() ImageData

Retrieve the underlying image data the grid is based upon.

Return type:

ImageData

get_texture() GLTexture

Create a new Texture resource from the underlying image data.

Return type:

GLTexture

get_texture_sequence() GLTextureGrid

Create a TextureGrid resource from the underlying image data.

It is recommended to use TextureGrid directly.

Return type:

GLTextureGrid

Patterns

class ImagePattern

Abstract image creation class.

abstractmethod create_image(
width: int,
height: int,
) _AbstractImage

Create an image of the given size.

Return type:

_AbstractImage

class CheckerImagePattern

Bases: ImagePattern

Create an image with a tileable checker image.

__init__(
color1=(150, 150, 150, 255),
color2=(200, 200, 200, 255),
)

Initialise with the given colors.

Parameters:
  • color1 – 4-tuple of ints in range [0,255] giving RGBA components of color to fill with. This color appears in the top-left and bottom-right corners of the image.

  • color2 – 4-tuple of ints in range [0,255] giving RGBA components of color to fill with. This color appears in the top-right and bottom-left corners of the image.

create_image(
width: int,
height: int,
) _AbstractImage

Create an image of the given size.

Return type:

_AbstractImage

class SolidColorImagePattern

Bases: ImagePattern

Creates an image filled with a solid RGBA color.

__init__(color=(0, 0, 0, 0))

Create a solid image pattern with the given color.

Parameters:

color – 4-tuple of ints in range [0,255] giving RGBA components of color to fill with.

create_image(
width: int,
height: int,
) _AbstractImage

Create an image of the given size.

Return type:

_AbstractImage

Functions

create(
width: int,
height: int,
pattern: ImagePattern | None = None,
) _AbstractImage

Create an image optionally filled with the given pattern.

Parameters:
width:

Width of image to create.

height:

Height of image to create.

pattern:

Optional pattern to fill image with. If unspecified, the image will initially be transparent.

Note

You can make no assumptions about the return type; usually it will be ImageData or CompressedImageData, but patterns are free to return any subclass of AbstractImage.

Return type:

_AbstractImage

load(
filename: str,
file: BinaryIO | None = None,
decoder: ImageDecoder | None = None,
) ImageData

Load an image from a file on disk, or from an open file-like object.

Parameters:
  • filename (str) – Used to guess the image format, and to load the file if file is unspecified.

  • file (BinaryIO | None) – Optional file containing the image data in any supported format.

  • decoder (ImageDecoder | None) – If unspecified, all decoders that are registered for the filename extension are tried. If none succeed, the exception from the first decoder is raised.

Return type:

ImageData

Note

You can make no assumptions about the return type; usually it will be ImageData or CompressedImageData, but decoders are free to return any subclass of AbstractImage.

load_animation(
filename: str,
file: BinaryIO | None = None,
decoder: ImageDecoder | None = None,
) Animation

Load an animation from a file on disk, or from an open file-like object.

Parameters:
  • filename (str) – Used to guess the animation format, and to load the file if file is unspecified.

  • file (BinaryIO | None) – Optional file containing the animation data in any supported format.

  • decoder (ImageDecoder | None) – If unspecified, all decoders that are registered for the filename extension are tried. If none succeed, the exception from the first decoder is raised.

Return type:

Animation

Exceptions

class ImageException
__init__(*args, **kwargs)
classmethod __new__(*args, **kwargs)
class ImageEncodeException
__init__(*args, **kwargs)
classmethod __new__(*args, **kwargs)
class ImageDecodeException
__init__(*args, **kwargs)
classmethod __new__(*args, **kwargs)