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

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() TextureBase

Retrieve a Texture instance with all mipmap levels filled in.

Return type:

TextureBase

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() TextureBase

A Texture view of this image.

Return type:

TextureBase

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.

BufferImage

alias of GLBufferImage

BufferImageMask

alias of GLBufferImageMask

DepthBufferImage

alias of GLDepthBufferImage

Texture

alias of GLTexture

TextureRegion

alias of GLTextureRegion

Image Sequences

Texture3D

alias of GLTexture3D

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

ImageData

alias of GLImageData

ImageDataRegion

alias of GLImageDataRegion

Other Classes

BufferManager

alias of GLBufferManager

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() TextureBase

Retrieve a Texture instance with all mipmap levels filled in.

Return type:

TextureBase

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

Retrieve a rectangular region of this image.

Return type:

AbstractImage

get_texture() TextureBase

A Texture view of this image.

Return type:

TextureBase

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 ImageEncodeException
__init__(*args, **kwargs)
__new__(**kwargs)
class ImageDecodeException
__init__(*args, **kwargs)
__new__(**kwargs)