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 a string:
format = 'RGBA'
pitch = rawimage.width * len(format)
pixels = rawimage.get_data(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(width, height)
Abstract class representing an image.
- Parameters
- widthint
Width of image
- heightint
Height of image
- anchor_xint
X coordinate of anchor, relative to left edge of image data
- anchor_yint
Y coordinate of anchor, relative to bottom edge of image data
- blit(x, y, z=0)
Draw this image to the active framebuffers.
The image will be drawn with the lower-left corner at (
x -
anchor_x,y -
anchor_y,z
).
- blit_into(source, x, y, z)
Draw source on 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) then you must pass a region of source to this method, typically using get_region().
- blit_to_texture(target, level, x, y, z=0)
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.
- Return type
New in version 1.1.
- get_mipmapped_texture()
Retrieve a
Texture
instance with all mipmap levels filled in.- Return type
New in version 1.1.
- get_region(x, y, width, height)
Retrieve a rectangular region of this image.
- Parameters
- xint
Left edge of region.
- yint
Bottom edge of region.
- widthint
Width of region.
- heightint
Height of region.
- Return type
- get_texture(rectangle=False)
A
Texture
view of this image.- Parameters
- rectanglebool
Unused. Kept for compatibility.
New in version 1.1.4..
- Return type
New in version 1.1.
- save(filename=None, file=None, encoder=None)
Save this image to a file.
- Parameters
- filenamestr
Used to set the image file format, and to open the output file if file is unspecified.
- filefile-like object or None
File to write image data to.
- encoderImageEncoder or None
If unspecified, all encoders matching the filename extension are tried. If all fail, the exception from the first one attempted is raised.
- anchor_x = 0
- anchor_y = 0
- class BufferImage(x, y, width, height)
Bases:
AbstractImage
An abstract framebuffer.
- get_image_data()
Get an ImageData view of this image.
Changes to the returned instance may or may not be reflected in this image.
- Return type
New in version 1.1.
- get_region(x, y, width, height)
Retrieve a rectangular region of this image.
- Parameters
- xint
Left edge of region.
- yint
Bottom edge of region.
- widthint
Width of region.
- heightint
Height of region.
- Return type
- 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(x, y, width, height)
Bases:
BufferImage
A single bit of the stencil buffer.
- format = 'L'
The format string used for image data.
- gl_format = 6401
The OpenGL format constant for image data.
- class ColorBufferImage(x, y, width, height)
Bases:
BufferImage
A color framebuffer.
This class is used to wrap the primary color buffer (i.e., the back buffer)
- blit_to_texture(target, level, x, y, z)
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
- rectanglebool
Unused. Kept for compatibility.
New in version 1.1.4..
- Return type
New in version 1.1.
- format = 'RGBA'
The format string used for image data.
- gl_format = 6408
The OpenGL format constant for image data.
- class DepthBufferImage(x, y, width, height)
Bases:
BufferImage
The depth buffer.
- blit_to_texture(target, level, x, y, z)
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
- rectanglebool
Unused. Kept for compatibility.
New in version 1.1.4..
- Return type
New in version 1.1.
- format = 'L'
The format string used for image data.
- gl_format = 6402
The OpenGL format constant for image data.
- class Texture(width, height, target, tex_id)
Bases:
AbstractImage
An image loaded into video memory that can be efficiently drawn to the framebuffer.
Typically, you will get an instance of Texture by accessing the texture member of any other AbstractImage.
- Parameters
- region_classclass (subclass of TextureRegion)
Class to use when constructing regions of this texture.
- tex_coordstuple
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.
- targetint
The GL texture target (e.g.,
GL_TEXTURE_2D
).- levelint
The mipmap level of this texture.
- region_class
alias of
TextureRegion
- bind_image_texture(unit, level=0, layered=False, layer=0, access=35002, fmt=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, y, z=0, width=None, height=None)
Draw this image to the active framebuffers.
The image will be drawn with the lower-left corner at (
x -
anchor_x,y -
anchor_y,z
).
- blit_into(source, x, y, z)
Draw source on 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) then you must pass a region of source to this method, typically using get_region().
- classmethod create(width, height, target=3553, internalformat=32856, min_filter=None, mag_filter=None, fmt=6408, blank_data=True)
Create a Texture
Create a Texture with the specified dimentions, target and format. On return, the texture will be bound.
- Parameters
- widthint
Width of texture in pixels.
- heightint
Height of texture in pixels.
- targetint
GL constant giving texture target to use, typically
GL_TEXTURE_2D
.- internalformatint
GL constant giving internal format of texture; for example,
GL_RGBA
. The internal format decides how the texture data will be stored internally. IfNone
, the texture will be created but not initialized.- min_filterint
The minifaction filter used for this texture, commonly
GL_LINEAR
orGL_NEAREST
- mag_filterint
The magnification filter used for this texture, commonly
GL_LINEAR
orGL_NEAREST
- fmtint
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_databool
Setting to True will initialize the texture data with all zeros. Setting False, will initialize Texture with no data.
- Return type
- get_image_data(z=0)
Get the image data of this texture.
Changes to the returned instance will not be reflected in this texture.
- Parameters
- zint
For 3D textures, the image slice to retrieve.
- Return type
- get_region(x, y, width, height)
Retrieve a rectangular region of this image.
- Parameters
- xint
Left edge of region.
- yint
Bottom edge of region.
- widthint
Width of region.
- heightint
Height of region.
- Return type
- get_texture(rectangle=False)
A
Texture
view of this image.- Parameters
- rectanglebool
Unused. Kept for compatibility.
New in version 1.1.4..
- Return type
New in version 1.1.
- get_transform(flip_x=False, flip_y=False, rotate=0)
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_xbool
If True, the returned image will be flipped horizontally.
- flip_ybool
If True, the returned image will be flipped vertically.
- rotateint
Degrees of clockwise rotation of the returned image. Only 90-degree increments are supported.
- Return type
- colors = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
- default_mag_filter = 9729
- default_min_filter = 9729
- images = 1
- level = 0
- tex_coords = (0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0)
- tex_coords_order = (0, 1, 2, 3)
- property uv
Tuple containing the left, bottom, right, top 2D texture coordinates.
- x = 0
- y = 0
- z = 0
- class DepthTexture(width, height, target, tex_id)
Bases:
Texture
A texture with depth samples (typically 24-bit).
- blit_into(source, x, y, z)
Draw source on 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) then you must pass a region of source to this method, typically using get_region().
- class TextureRegion(x, y, z, width, height, owner)
Bases:
Texture
A rectangular region of a texture, presented as if it were a separate texture.
- blit_into(source, x, y, z)
Draw source on 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) then you must pass a region of source to this method, typically using get_region().
- get_image_data()
Get the image data of this texture.
Changes to the returned instance will not be reflected in this texture.
- Parameters
- zint
For 3D textures, the image slice to retrieve.
- Return type
- get_region(x, y, width, height)
Retrieve a rectangular region of this image.
- Parameters
- xint
Left edge of region.
- yint
Bottom edge of region.
- widthint
Width of region.
- heightint
Height of region.
- Return type
- class TileableTexture(width, height, target, tex_id)
Bases:
Texture
A texture that can be tiled efficiently.
Use
create_for_image
classmethod to construct.- blit_tiled(x, y, z, width, height)
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.
- classmethod create_for_image(image)
- get_region(x, y, width, height)
Retrieve a rectangular region of this image.
- Parameters
- xint
Left edge of region.
- yint
Bottom edge of region.
- widthint
Width of region.
- heightint
Height of region.
- Return type
Image Sequences
- class AbstractImageSequence
Abstract sequence of images.
The sequence is useful for storing image animations or slices of a volume. For efficient access, use the texture_sequence member. The class also implements the sequence interface (__len__, __getitem__, __setitem__).
- get_animation(period, loop=True)
Create an animation over this image sequence for the given constant framerate.
- :Parameters
- periodfloat
Number of seconds to display each frame.
- loopbool
If True, the animation will loop continuously.
- Return type
Animation
New in version 1.1.
- get_texture_sequence()
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
TextureRegion
s within oneTexture
so as to minimise state changes.- get_texture_sequence()
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.
- Parameters
- item_widthint
Width of each texture in the sequence.
- item_heightint
Height of each texture in the sequence.
- property item_height
- property item_width
- class TextureGrid(grid)
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)]
- get(row, column)
- columns = 1
- item_height = 0
- item_width = 0
- items = ()
- rows = 1
- class Texture3D(width, height, target, tex_id)
Bases:
Texture
,UniformTextureSequence
A texture with more than one image slice.
Use create_for_images or create_for_image_grid classmethod to construct.
- classmethod create_for_image_grid(grid, internalformat=6408)
- classmethod create_for_images(images, internalformat=6408, blank_data=True)
- item_height = 0
- item_width = 0
- items = ()
Patterns
- class ImagePattern
Abstract image creation class.
- create_image(width, height)
Create an image of the given size.
- Parameters
- widthint
Width of image to create
- heightint
Height of image to create
- Return type
- class CheckerImagePattern(color1=(150, 150, 150, 255), color2=(200, 200, 200, 255))
Bases:
ImagePattern
Create an image with a tileable checker image.
- create_image(width, height)
Create an image of the given size.
- Parameters
- widthint
Width of image to create
- heightint
Height of image to create
- Return type
- class SolidColorImagePattern(color=(0, 0, 0, 0))
Bases:
ImagePattern
Creates an image filled with a solid color.
- create_image(width, height)
Create an image of the given size.
- Parameters
- widthint
Width of image to create
- heightint
Height of image to create
- Return type
Data
- class ImageData(width, height, fmt, data, pitch=None)
Bases:
AbstractImage
An image represented as a string of unsigned bytes.
- Parameters
- datastr
Pixel data, encoded according to format and pitch.
- formatstr
The format string to use when reading or writing data.
- pitchint
Number of bytes per row. Negative values indicate a top-to-bottom arrangement.
- blit(x, y, z=0, width=None, height=None)
Draw this image to the active framebuffers.
The image will be drawn with the lower-left corner at (
x -
anchor_x,y -
anchor_y,z
).
- blit_to_texture(target, level, x, y, z, internalformat=None)
Draw this image to 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, rectangle=False)
Create a texture containing this image.
- Parameters
- clsclass (subclass of Texture)
Class to construct.
- rectanglebool
Unused. kept for compatibility.
New in version 1.1.
- Return type
cls or cls.region_class
- get_data(fmt=None, pitch=None)
Get the byte data of the image.
- Parameters
- fmtstr
Format string of the return data.
- pitchint
Number of bytes per row. Negative values indicate a top-to-bottom arrangement.
New in version 1.1.
- get_image_data()
Get an ImageData view of this image.
Changes to the returned instance may or may not be reflected in this image.
- Return type
New in version 1.1.
- get_mipmapped_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
New in version 1.1.
- get_region(x, y, width, height)
Retrieve a rectangular region of this image data.
- Parameters
- xint
Left edge of region.
- yint
Bottom edge of region.
- widthint
Width of region.
- heightint
Height of region.
- Return type
- get_texture(rectangle=False)
A
Texture
view of this image.- Parameters
- rectanglebool
Unused. Kept for compatibility.
New in version 1.1.4..
- Return type
New in version 1.1.
- set_data(fmt, pitch, data)
Set the byte data of the image.
- Parameters
- fmtstr
Format string of the return data.
- pitchint
Number of bytes per row. Negative values indicate a top-to-bottom arrangement.
- datastr or sequence of bytes
Image data.
New in version 1.1.
- set_mipmap_image(level, image)
Set a mipmap image for a particular level.
The mipmap image will be applied to textures obtained via get_mipmapped_texture.
- Parameters
- levelint
Mipmap level to set image at, must be >= 1.
- imageAbstractImage
Image to set. Must have correct dimensions for that mipmap level (i.e., width >> level, height >> level)
- class CompressedImageData(width, height, gl_format, data, extension=None, decoder=None)
Bases:
AbstractImage
Image representing some compressed data suitable for direct uploading to driver.
- blit_to_texture(target, level, x, y, z)
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_mipmapped_texture()
Retrieve a
Texture
instance with all mipmap levels filled in.- Return type
New in version 1.1.
- get_texture(rectangle=False)
A
Texture
view of this image.- Parameters
- rectanglebool
Unused. Kept for compatibility.
New in version 1.1.4..
- Return type
New in version 1.1.
- set_mipmap_data(level, data)
Set data for a mipmap level.
Supplied data gives a compressed image for the given mipmap level. The image must 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.
- Parameters
- levelint
Level of mipmap image to set.
- datasequence
String or array/list of bytes giving compressed image data. Data must be in same format as specified in constructor.
- class ImageDataRegion(x, y, width, height, image_data)
Bases:
ImageData
- get_data(fmt=None, pitch=None)
Get the byte data of the image.
- Parameters
- fmtstr
Format string of the return data.
- pitchint
Number of bytes per row. Negative values indicate a top-to-bottom arrangement.
New in version 1.1.
- get_region(x, y, width, height)
Retrieve a rectangular region of this image data.
- Parameters
- xint
Left edge of region.
- yint
Bottom edge of region.
- widthint
Width of region.
- heightint
Height of region.
- Return type
- set_data(fmt, pitch, data)
Set the byte data of the image.
- Parameters
- fmtstr
Format string of the return data.
- pitchint
Number of bytes per row. Negative values indicate a top-to-bottom arrangement.
- datastr or sequence of bytes
Image data.
New in version 1.1.
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.- get_buffer_mask()
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
- get_color_buffer()
Get the color buffer.
- Return type
- get_depth_buffer()
Get the depth buffer.
- Return type
- static get_viewport()
Get the current OpenGL viewport dimensions.
- Return type
4-tuple of float.
- Returns
Left, top, right and bottom dimensions.
- class ImageGrid(image, rows, columns, item_width=None, item_height=None, row_padding=0, column_padding=0)
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)
- get_image_data()
Get an ImageData view of this image.
Changes to the returned instance may or may not be reflected in this image.
- Return type
New in version 1.1.
- get_texture(rectangle=False)
A
Texture
view of this image.- Parameters
- rectanglebool
Unused. Kept for compatibility.
New in version 1.1.4..
- Return type
New in version 1.1.
- get_texture_sequence()
Get a TextureSequence.
- Return type
TextureSequence
New in version 1.1.
Functions
- create(width, height, pattern=None)
Create an image optionally filled with the given pattern.
- Parameters
- widthint
Width of image to create
- heightint
Height of image to create
- patternImagePattern or None
Pattern to fill image with. If unspecified, the image will initially be transparent.
- Return type
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()
Get the buffer manager for the current OpenGL context.
- Return type
- load(filename, file=None, decoder=None)
Load an image from a file.
- Parameters
- filenamestr
Used to guess the image format, and to load the file if file is unspecified.
- filefile-like object or None
Source of image data in any supported format.
- decoderImageDecoder or 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(filename, file=None, decoder=None)
Load an animation from a file.
Currently, the only supported format is GIF.
- Parameters
- filenamestr
Used to guess the animation format, and to load the file if file is unspecified.
- filefile-like object or None
File object containing the animation stream.
- decoderImageDecoder or 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
- get_max_texture_size()
Query the maximum texture size available
Exceptions
- class ImageException
- class ImageEncodeException
- class ImageDecodeException