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.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

Images

class AbstractImage

Abstract class representing an image.

__init__(width: int, height: int)

Initialized in subclass.

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

Draw this image to the active framebuffer.

The image will be drawn with the lower-left corner at (x - anchor_x, y - anchor_y, z). :rtype: None

Note

This is a relatively slow method, as a full OpenGL setup and draw call is required for each blit. For performance, consider creating a Sprite from the Image, and adding it to a Batch.

abstract blit_into(source, x: int, y: int, z: int) None

Draw the provided source data INTO this image.

source will be copied into this image such that its anchor point is aligned with the x and y parameters. If this image is a 3D Texture, the z coordinate gives the image slice to copy into.

Note that if source is larger than this image (or the positioning would cause the copy to go out of bounds), an exception may be raised. To prevent errors, you can use the source.get_region(x, y, w, h) method to get a smaller section that will fall within the bounds of this image.

Return type:

None

abstract blit_to_texture(
target: int,
level: int,
x: int,
y: int,
z: int,
internalformat: int = None,
) None

Draw this image on the currently bound texture at target.

This image is copied into the texture such that this image’s anchor point is aligned with the given x and y coordinates of the destination texture. If the currently bound texture is a 3D texture, the z coordinate gives the image slice to blit into.

Return type:

None

abstract 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

abstract get_mipmapped_texture() Texture

Retrieve a Texture instance with all mipmap levels filled in.

Return type:

Texture

abstract get_region(
x: int,
y: int,
width: int,
height: int,
) AbstractImage

Retrieve a rectangular region of this image.

Return type:

AbstractImage

abstract get_texture(rectangle: bool = False) Texture

A Texture view of this image.

Parameters:

rectangle (bool) – Unused. Kept for backwards compatibility.

Return type:

Texture

save(
filename: str | None = None,
file: BinaryIO | None = None,
encoder: ImageEncoder | None = None,
) None

Save this image to a file.

Parameters:
  • filename (str | None) – Used to set the image file format, and to open the output file if file is unspecified.

  • file (BinaryIO | None) – An optional file-like object to write image data to.

  • encoder (ImageEncoder | None) – If unspecified, all encoders matching the filename extension are tried, or all encoders if no filename is provided. If all fail, the exception from the first one attempted is raised.

Return type:

None

anchor_x: int = 0

X coordinate of anchor, relative to left edge of image data.

anchor_y: int = 0

Y coordinate of anchor, relative to bottom edge of image data.

class BufferImage

Bases: AbstractImage

An abstract “default” framebuffer.

__init__(x, y, width, height)

Initialized in subclass.

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

Draw this image to the active framebuffer.

The image will be drawn with the lower-left corner at (x - anchor_x, y - anchor_y, z). :rtype: None

Note

This is a relatively slow method, as a full OpenGL setup and draw call is required for each blit. For performance, consider creating a Sprite from the Image, and adding it to a Batch.

blit_into(source, x: int, y: int, z: int) None

Draw the provided source data INTO this image.

source will be copied into this image such that its anchor point is aligned with the x and y parameters. If this image is a 3D Texture, the z coordinate gives the image slice to copy into.

Note that if source is larger than this image (or the positioning would cause the copy to go out of bounds), an exception may be raised. To prevent errors, you can use the source.get_region(x, y, w, h) method to get a smaller section that will fall within the bounds of this image.

Return type:

None

blit_to_texture(
target: int,
level: int,
x: int,
y: int,
z: int,
internalformat: int = None,
)

Draw this image on the currently bound texture at target.

This image is copied into the texture such that this image’s anchor point is aligned with the given x and y coordinates of the destination texture. If the currently bound texture is a 3D texture, the z coordinate gives the image slice to blit into.

get_image_data()

Get an ImageData view of this image.

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

get_mipmapped_texture() Texture

Retrieve a Texture instance with all mipmap levels filled in.

Return type:

Texture

get_region(x, y, width, height)

Retrieve a rectangular region of this image.

get_texture(rectangle: bool = False) Texture

A Texture view of this image.

Parameters:

rectangle (bool) – Unused. Kept for backwards compatibility.

Return type:

Texture

format = ''

The format string used for image data.

gl_buffer = 1029

The OpenGL read and write target for this buffer.

gl_format = 0

The OpenGL format constant for image data.

owner = None
class BufferImageMask

Bases: BufferImage

A single bit of the stencil buffer.

format = 'R'

The format string used for image data.

gl_format = 6401

The OpenGL format constant for image data.

class ColorBufferImage

Bases: BufferImage

A color framebuffer.

This class is used to wrap the primary color buffer (i.e., the back buffer)

blit_to_texture(
target: int,
level: int,
x: int,
y: int,
z: int,
internalformat: int = None,
)

Draw this image on the currently bound texture at target.

This image is copied into the texture such that this image’s anchor point is aligned with the given x and y coordinates of the destination texture. If the currently bound texture is a 3D texture, the z coordinate gives the image slice to blit into.

get_texture(rectangle=False)

A Texture view of this image.

Parameters:

rectangle – Unused. Kept for backwards compatibility.

format = 'RGBA'

The format string used for image data.

gl_format = 6408

The OpenGL format constant for image data.

class DepthBufferImage

Bases: BufferImage

The depth buffer.

blit_to_texture(
target: int,
level: int,
x: int,
y: int,
z: int,
internalformat: int = None,
)

Draw this image on the currently bound texture at target.

This image is copied into the texture such that this image’s anchor point is aligned with the given x and y coordinates of the destination texture. If the currently bound texture is a 3D texture, the z coordinate gives the image slice to blit into.

get_texture(rectangle=False)

A Texture view of this image.

Parameters:

rectangle – Unused. Kept for backwards compatibility.

format = 'R'

The format string used for image data.

gl_format = 6402

The OpenGL format constant for image data.

class Texture

Bases: AbstractImage

An image loaded into GPU memory

Typically, you will get an instance of Texture by accessing calling the get_texture() method of any AbstractImage class (such as ImageData).

region_class

The class to use when constructing regions of this texture. The class should be a subclass of TextureRegion.

alias of TextureRegion

__init__(width: int, height: int, target: int, tex_id: int) None

Initialized in subclass.

bind(texture_unit: int = 0) None

Bind to a specific Texture Unit by number.

Return type:

None

bind_image_texture(
unit: int,
level: int = 0,
layered: bool = False,
layer: int = 0,
access: int = 35002,
fmt: int = 34836,
)

Bind as an ImageTexture for use with a ComputeShaderProgram.

Note

OpenGL 4.3, or 4.2 with the GL_ARB_compute_shader extention is required.

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

Blit the texture to the screen.

This is a costly operation, and should not be used for performance critical code. Blitting a texture requires binding it, setting up throwaway buffers, creating a VAO, uploading attribute data, and then making a single draw call. This is quite wasteful and slow, so blitting should not be used for more than a few images. This method is provided to assist with debugging, but not intended for drawing of multiple images.

Instead, consider creating a Sprite with the Texture, and drawing it as part of a larger Batch.

Return type:

None

blit_into(source: AbstractImage, x: int, y: int, z: int)

Draw the provided source data INTO this image.

source will be copied into this image such that its anchor point is aligned with the x and y parameters. If this image is a 3D Texture, the z coordinate gives the image slice to copy into.

Note that if source is larger than this image (or the positioning would cause the copy to go out of bounds), an exception may be raised. To prevent errors, you can use the source.get_region(x, y, w, h) method to get a smaller section that will fall within the bounds of this image.

blit_to_texture(
target: int,
level: int,
x: int,
y: int,
z: int,
internalformat: int = None,
)

Draw this image on the currently bound texture at target.

This image is copied into the texture such that this image’s anchor point is aligned with the given x and y coordinates of the destination texture. If the currently bound texture is a 3D texture, the z coordinate gives the image slice to blit into.

classmethod create(
width: int,
height: int,
target: int = 3553,
internalformat: int | None = 32856,
min_filter: int | None = None,
mag_filter: int | None = None,
fmt: int = 6408,
blank_data: bool = True,
) Texture

Create a Texture

Create a Texture with the specified dimentions, target and format. On return, the texture will be bound.

Parameters:
  • width (int) – Width of texture in pixels.

  • height (int) – Height of texture in pixels.

  • target (int) – GL constant giving texture target to use, typically GL_TEXTURE_2D.

  • internalformat (int | None) – GL constant giving internal format of texture; for example, GL_RGBA. The internal format decides how the texture data will be stored internally. If None, the texture will be created but not initialized.

  • min_filter (int | None) – The minifaction filter used for this texture, commonly GL_LINEAR or GL_NEAREST

  • mag_filter (int | None) – The magnification filter used for this texture, commonly GL_LINEAR or GL_NEAREST

  • fmt (int) – GL constant giving format of texture; for example, GL_RGBA. The format specifies what format the pixel data we’re expecting to write to the texture and should ideally be the same as for internal format.

  • blank_data (bool) – If True, initialize the texture data with all zeros. If False, do not pass initial data.

Return type:

Texture

delete() None

Delete this texture and the memory it occupies.

Textures are invalid after deletion, and may no longer be used.

Return type:

None

get_image_data(z: int = 0) ImageData

Get the image data of this texture.

Bind the texture, and read the pixel data back from the GPU. This can be a somewhat costly operation.

Modifying the returned ImageData object has no effect on the texture itself. Uploading ImageData back to the GPU/texture can be done with the blit_into() method.

Parameters:

z (int) – For 3D textures, the image slice to retrieve.

Return type:

ImageData

get_mipmapped_texture() Texture

Retrieve a Texture instance with all mipmap levels filled in.

Return type:

Texture

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

Retrieve a rectangular region of this image.

Return type:

TextureRegion

get_texture(rectangle: bool = False) Texture

A Texture view of this image.

Parameters:

rectangle (bool) – Unused. Kept for backwards compatibility.

Return type:

Texture

get_transform(
flip_x: bool = False,
flip_y: bool = False,
rotate: Literal[0, 90, 180, 270, 360] = 0,
) TextureRegion

Create a copy of this image applying a simple transformation.

The transformation is applied to the texture coordinates only; get_image_data() will return the untransformed data. The transformation is applied around the anchor point.

Parameters:
  • flip_x (bool) – If True, the returned image will be flipped horizontally.

  • flip_y (bool) – If True, the returned image will be flipped vertically.

  • rotate (Literal[0, 90, 180, 270, 360]) – Degrees of clockwise rotation of the returned image. Only 90-degree increments are supported.

Return type:

TextureRegion

colors = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

The GL texture target (e.g., GL_TEXTURE_2D).

default_mag_filter = 9729

The default magnification filter. Defaults to GL_LINEAR. If a texture is created without specifying a filter, this default will be used.

default_min_filter = 9729

The default minification filter. Defaults to GL_LINEAR. If a texture is created without specifying a filter, this default will be used.

images = 1
level: int = 0

The mipmap level of this texture.

target: int

The GL texture target (e.g., GL_TEXTURE_2D).

tex_coords = (0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0)

12-tuple of float, named (u1, v1, r1, u2, v2, r2, …). u, v, r give the 3D texture coordinates for vertices 1-4. The vertices are specified in the order bottom-left, bottom-right, top-right and top-left.

tex_coords_order: tuple[int, int, int, int] = (0, 1, 2, 3)

The default vertex winding order for a quad. This defaults to counter-clockwise, starting at the bottom-left.

property uv: tuple[float, float, float, float]

Tuple containing the left, bottom, right, top 2D texture coordinates.

x: int = 0
y: int = 0
z: int = 0
class TextureRegion

Bases: Texture

A rectangular region of a texture, presented as if it were a separate texture.

__init__(
x: int,
y: int,
z: int,
width: int,
height: int,
owner: Texture,
)

Initialized in subclass.

blit_into(
source: AbstractImage,
x: int,
y: int,
z: int,
) None

Draw the provided source data INTO this image.

source will be copied into this image such that its anchor point is aligned with the x and y parameters. If this image is a 3D Texture, the z coordinate gives the image slice to copy into.

Note that if source is larger than this image (or the positioning would cause the copy to go out of bounds), an exception may be raised. To prevent errors, you can use the source.get_region(x, y, w, h) method to get a smaller section that will fall within the bounds of this image.

Return type:

None

delete() None

Deleting a TextureRegion has no effect. Operate on the owning texture instead.

Return type:

None

get_image_data()

Get the image data of this texture.

Bind the texture, and read the pixel data back from the GPU. This can be a somewhat costly operation.

Modifying the returned ImageData object has no effect on the texture itself. Uploading ImageData back to the GPU/texture can be done with the blit_into() method.

Parameters:

z – For 3D textures, the image slice to retrieve.

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

Retrieve a rectangular region of this image.

Return type:

TextureRegion

class TileableTexture

Bases: Texture

A texture that can be tiled efficiently.

Use create_for_image classmethod to construct.

blit_tiled(x: int, y: int, z: int, width: int, height: int) None

Blit this texture tiled over the given area.

The image will be tiled with the bottom-left corner of the destination rectangle aligned with the anchor point of this texture.

Return type:

None

classmethod create_for_image(
image: AbstractImage,
) Texture
Return type:

Texture

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

Retrieve a rectangular region of this image.

Image Sequences

class AbstractImageSequence

Abstract sequence of images.

Image sequence are useful for storing image animations or slices of a volume. The class implements the sequence interface (__len__, __getitem__, __setitem__).

get_animation(
period: float,
loop: bool = True,
) Animation

Create an animation over this image sequence for the given constant framerate.

Parameters:
  • period (float) – Number of seconds to display each frame.

  • loop (bool) – If True, the animation will loop continuously.

Return type:

Animation

abstract get_texture_sequence() TextureSequence

Get a TextureSequence.

Return type:

TextureSequence

New in version 1.1.

class TextureSequence

Bases: AbstractImageSequence

Interface for a sequence of textures.

Typical implementations store multiple Texture to minimise state changes.

get_texture_sequence() TextureSequence

Get a TextureSequence.

Return type:

TextureSequence

New in version 1.1.

class UniformTextureSequence

Bases: TextureSequence

Interface for a sequence of textures, each with the same dimensions.

class TextureGrid

Bases: TextureRegion, UniformTextureSequence

A texture containing a regular grid of texture regions.

To construct, create an ImageGrid first:

image_grid = ImageGrid(...)
texture_grid = TextureGrid(image_grid)

The texture grid can be accessed as a single texture, or as a sequence of TextureRegion. When accessing as a sequence, you can specify integer indexes, in which the images are arranged in rows from the bottom-left to the top-right:

# assume the texture_grid is 3x3:
current_texture = texture_grid[3] # get the middle-left image

You can also specify tuples in the sequence methods, which are addressed as row, column:

# equivalent to the previous example:
current_texture = texture_grid[1, 0]

When using tuples in a slice, the returned sequence is over the rectangular region defined by the slice:

# returns center, center-right, center-top, top-right images in that
# order:
images = texture_grid[(1,1):]
# equivalent to
images = texture_grid[(1,1):(3,3)]
__init__(grid: ImageGrid) None

Initialized in subclass.

get(row: int, column: int)
columns: int
item_height: int
item_width: int
items: list
rows: int
class Texture3D

Bases: Texture, UniformTextureSequence

A texture with more than one image slice.

Use the create_for_images() or create_for_image_grid() classmethod to construct a Texture3D.

classmethod create_for_image_grid(grid, internalformat=6408)
classmethod create_for_images(images, internalformat=6408, blank_data=True)
item_height: int = 0
item_width: int = 0
items: tuple

Patterns

class ImagePattern

Abstract image creation class.

abstract 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

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

Initialise 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).

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

Draw this image to the active framebuffer.

The image will be drawn with the lower-left corner at (x - anchor_x, y - anchor_y, z). :rtype: None

Note

This is a relatively slow method, as a full OpenGL setup and draw call is required for each blit. For performance, consider creating a Sprite from the Image, and adding it to a Batch.

blit_into(source, x: int, y: int, z: int) None

Draw the provided source data INTO this image.

source will be copied into this image such that its anchor point is aligned with the x and y parameters. If this image is a 3D Texture, the z coordinate gives the image slice to copy into.

Note that if source is larger than this image (or the positioning would cause the copy to go out of bounds), an exception may be raised. To prevent errors, you can use the source.get_region(x, y, w, h) method to get a smaller section that will fall within the bounds of this image.

Return type:

None

blit_to_texture(
target: int,
level: int,
x: int,
y: int,
z: int,
internalformat: int = None,
)

Draw this image to the currently bound texture at target.

This image’s anchor point will be aligned to the given x and y coordinates. If the currently bound texture is a 3D texture, the z parameter gives the image slice to blit into.

If internalformat is specified, glTexImage is used to initialise the texture; otherwise, glTexSubImage is used to update a region.

create_texture(
cls: type[pyglet.image.Texture],
rectangle: bool = False,
) Texture

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

Return type:

Texture

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_data(fmt: str | None = None, pitch: int | None = None) bytes

Get the byte data of the image. :rtype: bytes

Warning

This method is deprecated and will be removed in the next version. Use get_bytes() instead.

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_mipmapped_texture() Texture

Return a Texture with mipmaps.

If set_mipmap_Image has been called with at least one image, the set of images defined will be used. Otherwise, mipmaps will be automatically generated.

Return type:

Texture

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

Retrieve a rectangular region of this image data.

Return type:

ImageDataRegion

get_texture(rectangle: bool = False) Texture

A Texture view of this image.

Parameters:

rectangle (bool) – Unused. Kept for backwards compatibility.

Return type:

Texture

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

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

Set the byte data of the image. :rtype: None

Warning

This method is deprecated and will be removed in the next version. Use set_bytes() instead.

set_mipmap_image(level: int, image: AbstractImage) None

Set a user-defined mipmap image for a particular level.

These mipmap images will be applied to textures obtained via get_mipmapped_texture(), instead of automatically generated images for each level.

Parameters:
  • level (int) – Mipmap level to set image at, must be >= 1.

  • image (AbstractImage) – Image to set. Must have correct dimensions for that mipmap level (i.e., width >> level, height >> level)

Return type:

None

property format: str

Format string of the data. Read-write.

class CompressedImageData

Bases: AbstractImage

Compressed image data suitable for direct uploading to GPU.

__init__(
width: int,
height: int,
gl_format: int,
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.

  • gl_format (int) – GL constant giving the format of the compressed data. For example: GL_COMPRESSED_RGBA_S3TC_DXT5_EXT.

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

  • extension (str | None) – If specified, gives the name of a GL 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

Draw this image to the active framebuffer.

The image will be drawn with the lower-left corner at (x - anchor_x, y - anchor_y, z). :rtype: None

Note

This is a relatively slow method, as a full OpenGL setup and draw call is required for each blit. For performance, consider creating a Sprite from the Image, and adding it to a Batch.

blit_into(source, x: int, y: int, z: int) None

Draw the provided source data INTO this image.

source will be copied into this image such that its anchor point is aligned with the x and y parameters. If this image is a 3D Texture, the z coordinate gives the image slice to copy into.

Note that if source is larger than this image (or the positioning would cause the copy to go out of bounds), an exception may be raised. To prevent errors, you can use the source.get_region(x, y, w, h) method to get a smaller section that will fall within the bounds of this image.

Return type:

None

blit_to_texture(
target: int,
level: int,
x: int,
y: int,
z: int,
internalformat: int = None,
)

Draw this image on the currently bound texture at target.

This image is copied into the texture such that this image’s anchor point is aligned with the given x and y coordinates of the destination texture. If the currently bound texture is a 3D texture, the z coordinate gives the image slice to blit into.

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_mipmapped_texture() Texture

Retrieve a Texture instance with all mipmap levels filled in.

Return type:

Texture

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

Retrieve a rectangular region of this image.

Return type:

AbstractImage

get_texture(rectangle=False) Texture

A Texture view of this image.

Parameters:

rectangle – Unused. Kept for backwards compatibility.

Return type:

Texture

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

class ImageDataRegion

Bases: ImageData

__init__(x, y, width, height, image_data)

Initialise image data.

Parameters:
  • width – Width of image data

  • height – 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).

get_bytes(fmt=None, pitch=None)

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 – If provided, get the data in another format.

  • pitch – 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.

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, y, width, height)

Retrieve a rectangular region of this image data.

set_bytes(fmt, pitch, data)

Set the byte data of the image.

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

  • pitch – 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 – Image data as bytes.

Other Classes

class BufferManager

Manages the set of framebuffers for a context.

Use get_buffer_manager() to obtain the instance of this class for the current context.

__init__()
get_buffer_mask() BufferImageMask

Get a free bitmask buffer.

A bitmask buffer is a buffer referencing a single bit in the stencil buffer. If no bits are free, ImageException is raised. Bits are released when the bitmask buffer is garbage collected.

Return type:

BufferImageMask

get_color_buffer() ColorBufferImage

Get the color buffer.

Return type:

ColorBufferImage

get_depth_buffer() DepthBufferImage

Get the depth buffer.

Return type:

DepthBufferImage

static get_viewport() tuple

Get the current OpenGL viewport dimensions (left, bottom, right, top).

Return type:

tuple

class ImageGrid

Bases: AbstractImage, AbstractImageSequence

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. The most useful applications are to access the grid as a TextureGrid:

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

or as a Texture3D:

image_grid = ImageGrid(...)
texture_3d = Texture3D.create_for_image_grid(image_grid)
__init__(
image: AbstractImage,
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 (AbstractImage) – 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.

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

Draw this image to the active framebuffer.

The image will be drawn with the lower-left corner at (x - anchor_x, y - anchor_y, z). :rtype: None

Note

This is a relatively slow method, as a full OpenGL setup and draw call is required for each blit. For performance, consider creating a Sprite from the Image, and adding it to a Batch.

blit_into(source, x: int, y: int, z: int) None

Draw the provided source data INTO this image.

source will be copied into this image such that its anchor point is aligned with the x and y parameters. If this image is a 3D Texture, the z coordinate gives the image slice to copy into.

Note that if source is larger than this image (or the positioning would cause the copy to go out of bounds), an exception may be raised. To prevent errors, you can use the source.get_region(x, y, w, h) method to get a smaller section that will fall within the bounds of this image.

Return type:

None

blit_to_texture(
target: int,
level: int,
x: int,
y: int,
z: int,
internalformat: int = None,
)

Draw this image on the currently bound texture at target.

This image is copied into the texture such that this image’s anchor point is aligned with the given x and y coordinates of the destination texture. If the currently bound texture is a 3D texture, the z coordinate gives the image slice to blit into.

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_mipmapped_texture() Texture

Retrieve a Texture instance with all mipmap levels filled in.

Return type:

Texture

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

Retrieve a rectangular region of this image.

Return type:

AbstractImage

get_texture(rectangle: bool = False) Texture

A Texture view of this image.

Parameters:

rectangle (bool) – Unused. Kept for backwards compatibility.

Return type:

Texture

get_texture_sequence() TextureGrid

Get a TextureSequence.

Return type:

TextureSequence

New in version 1.1.

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.

Return type:

AbstractImage

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.

get_buffer_manager() BufferManager

Get the buffer manager for the current OpenGL context.

Return type:

BufferManager

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

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:

AbstractImage

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

get_max_texture_size() int

Query the maximum texture size available

Return type:

int

Exceptions

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