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.

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.

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

Retrieve a rectangular region of this image.

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)

get_texture()

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.

get_texture()

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

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.

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.

class TileableTexture

Bases: Texture

A texture that can be tiled efficiently.

Use create_for_image classmethod to construct.

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

class TextureSequence

Bases: AbstractImageSequence

Interface for a sequence of textures.

Typical implementations store multiple Texture to minimise state changes.

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

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.

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.

Data

class ImageData

Bases: AbstractImage

An image represented as a string of unsigned bytes.

property format: str

Format string of the data. Read-write.

class CompressedImageData

Bases: AbstractImage

Compressed image data suitable for direct uploading to GPU.

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

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

Functions

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)