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:
_AbstractImageAn 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',
Initialize image data.
- Parameters:
width (
int) – Width of image dataheight (
int) – Height of image datafmt (
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 towidth * 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.
- 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:
- create_texture(
- cls: type[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
fmtandpitcharguments. For example, if the image format isRGBA, and you wish to get the byte data inRGBformat:rgb_pitch = my_image.width * len('RGB') rgb_img_bytes = my_image.get_bytes(fmt='RGB', pitch=rgb_pitch)
The image
pitchmay be negative, so be sure to check that when converting to another format. Switching the sign of thepitchwill cause the image to appear “upside-down”.- Parameters:
- Return type:
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:
- get_region( ) ImageDataRegion
Retrieve a rectangular region of this image data.
- Return type:
- get_texture() GLTexture
- Return type:
GLTexture
- class ImageDataRegion
Bases:
ImageDataA region of image data taken from an existing ImageData or region.
- __init__( ) None
Initialize image data.
- Parameters:
width (
int) – Width of image dataheight (
int) – Height of image datafmt – 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
fmtandpitcharguments. For example, if the image format isRGBA, and you wish to get the byte data inRGBformat:rgb_pitch = my_image.width * len('RGB') rgb_img_bytes = my_image.get_bytes(fmt='RGB', pitch=rgb_pitch)
The image
pitchmay be negative, so be sure to check that when converting to another format. Switching the sign of thepitchwill cause the image to appear “upside-down”.- Parameters:
- Return type:
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( ) ImageDataRegion
Retrieve a rectangular region of this image data.
- Return type:
- class CompressedImageData
Bases:
_AbstractImageCompressed 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,
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.
- create_texture(
- cls: type[GLCompressedTexture],
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:
- get_region( ) _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_textureare generated automatically.- Return type:
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
TextureGridgenerated 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
TextureGriddirectly.- __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,
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_texture() GLTexture
Create a new Texture resource from the underlying image data.
- Return type:
GLTexture
- get_texture_sequence() GLTextureGrid
Create a
TextureGridresource from the underlying image data.It is recommended to use
TextureGriddirectly.- Return type:
GLTextureGrid
Patterns
- class ImagePattern
Abstract image creation class.
- class CheckerImagePattern
Bases:
ImagePatternCreate 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:
ImagePatternCreates 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.
Functions
- create(
- width: int,
- height: int,
- pattern: ImagePattern | None = None,
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( ) 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 iffileis 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:
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( ) 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 iffileis 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: