Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Python's pyglet library is a cross-platform windowing and multimedia library for creating games and other visually rich applications. Windowing, user interface event handling, joysticks, OpenGL graphics, loading images and videos, and sound and music playback are all supported. pyglet is compatible with Windows, Mac OS X, and Linux. In this article, we are going to talk about pyglet.image. So let us dive in!
pyglet.image
pyglet.image module is used for Image load, capture, and high-level texture functions.
Following are some basic functionality of pyglet.image:
To load an image:
from pyglet import image
pic = image.load('picture.png')
PNG, BMP, GIF, JPG, and a variety of other image file types are supported, depending on the operating system. Instead of a filename, load an image from a file-like object:
pic = image.load('hint.jpg', file=fileobj)
Based on the file extension, the hint assists the module in finding an appropriate decoder to use. It is purely optional.
Images can be used directly by most other pyglet modules once they've been loaded. You can find the width and height of all images here:
width, height = pic.width, pic.height
You can extract a region of an image (keeping the original image intact and efficiently sharing memory):
subimage = pic.get_region(x, y, width, height)
Always keep in mind that y-coordinates are increasing upwards.
Example Code for Loading Image
A window is a "heavyweight" object that consumes resources from the operating system. Windows can be set to appear as floating regions or to fill the entire screen (fullscreen). The resource module of pyglet is used to load a file or resource. This module allows applications to specify a resource search path. Relative paths are assumed to be relative to the __main__ module of the application.
With the help of the commands listed below, we can create a window object:
# importing pyglet module
import pyglet
import pyglet.window.key as key
# width of window
width = 500
# height of window
height = 500
# caption, i.e., title of the window
title = "Coding Ninjas"
# creating a window
window = pyglet.window.Window(width, height, title)
# text
text = "Welcome to Coding Ninjas"
# creating label with following properties
# font = cooper
# position = 250, 150
# anchor position = center
label = pyglet.text.Label(text,
font_name ='Cooper',
font_size = 16,
x = 250,
y = 150,
anchor_x ='center',
anchor_y ='center')
# creating a batch
batch = pyglet.graphics.Batch()
# loading coding ninjas image
image = pyglet.image.load('cn.png')
# creating sprite object
# it is instance of an image displayed on-screen
sprite = pyglet.sprite.Sprite(image, x = 200, y = 230)
# on draw event
@window.event
def on_draw():
# clear the window
window.clear()
# draw the label
label.draw()
# draw the image on screen
sprite.draw()
# key press event
@window.event
def on_key_press(symbol, modifier):
# key "C" get press
if symbol == key.C:
# printing the message
print("Key : C is pressed")
# image for icon
img = image = pyglet.resource.image("cn.png")
# setting image as icon
window.set_icon(img)
# loading image resource
value = pyglet.resource.image("cn.png")
# setting text of label
label.text = str(value)
# start running the application
pyglet.app.run()
Drawing images
To draw an image on the screen at a specific location:
pic.blit(x, y, z)
This assumes you've used the right view transform and projection.
Some images have an inherent "anchor point," which is the point where the x and y coordinates will be aligned when the image is drawn. The anchor point is set to the image's lower-left corner by default. The anchor point can be used to centre an image at a specific location, for example:
You can access the image as a texture if you're using OpenGL directly:
texture = pic.get_texture()
This is the quickest way to get a texture; some images are loaded as textures right away, while others go through an intermediate stage. To use a texture with pyglet.gl, follow these steps:
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 get at an image's raw pixel data, do the following:
rawimage = pic.get_image_data()
This will be a very quick operation if the image was just loaded; however, if the image is a texture, it will be a relatively expensive readback operation. A string can be used to access the pixels:
Characters in "format" strings indicate the byte order of each colour component. If rawimage.format is 'RGBA,' for example, there are four colour components in that order: red, green, blue, and alpha. 'RGB,' 'LA' (luminance, alpha), and 'I' are also common format strings (intensity).
The number of bytes in a row determines an image's "pitch" (this may validly be more than the number required to make up the image's width; it is common to see this for word alignment). The rows of the image are ordered from top to bottom if "pitch" is negative; otherwise, they are ordered from bottom to top.
Using the format and pitch specified in ImageData.format and ImageData.pitch to retrieve data eliminates the need for data conversion (assuming you can use the data in this arbitrary format).
Classes
Images
class AbstractImage(width, height): Abstract class that represents an image.
class BufferImage(x, y, width, height): Abstract frameBuffer.
class BufferImageMask(x, y, width, height): A single bit of the stencil buffer.
class ColorBufferImage(x, y, width, height): A color frameBuffer. This class wraps the primary colour buffer (the back buffer) as well as any of the auxiliary buffers.
classDepthBufferImage(x, y, width, height): Depth buffer.
classTexture(width, height, target, id): An image that can be efficiently drawn to the framebuffer from video memory.
In most cases, you can get a Texture instance by accessing the texture member of another AbstractImage.
class DepthTexture(width, height, target, id): A texture with depth samples (typically 24-bit).
class TextureRegion(x, y, z, width, height, owner): A rectangular region of a texture that appears to be its own texture.
class TileableTexture(width, height, target, id): A texture that can be tiled efficiently.
Image Sequences
class AbstractImageSequence: Abstract sequence of images.
The sequence can be used to save image animations or volume slices. Use the texture sequence member for quick access. The sequence interface is also implemented (__len__, __getitem__, __setitem__).
class TextureSequence: Interface for a sequence of textures.
To minimise state changes, most implementations store multiple TextureRegions within a single Texture.
class UniformTextureSequence: Interface for a sequence of textures, each with the same dimensions.
class TextureGrid(grid): A texture containing a regular grid of texture regions.
class Texture3D(width, height, target, id): A texture with more than one image slice.
Patterns
class ImagePattern: Abstract image creation class.
class CheckerImagePattern(color1=(150, 150, 150, 255), color2=(200, 200, 200, 255)): Create an image with a tileable checker image.
class SolidColorImagePattern(color=(0, 0, 0, 0)): Creates an image filled with a solid color.
Data
class ImageData(width, height, format, data, pitch=None): An image represented as a string of unsigned bytes.
class CompressedImageData(width, height, gl_format, data, extension=None, decoder=None): Image representing some compressed data suitable for direct uploading to driver.
Other Classes
classBufferManager: Manages the set of framebuffers for a context.
Use get_buffer_manager() to obtain the instance of this class for the current context.
The x and y properties can be changed to move the sprite. The sprite's rotation, scale, and opacity are all determined by other properties.
Is pyglet faster than pygame?
Pyglet is definitely faster and has better performance than pygame, and nowadays, speed is always a concern when developing games.
What is pyglet used for?
Pyglet is a Python library that provides an object-oriented application programming interface for developing games and other multimedia applications.
Is pyglet open-source?
Pyglet is released under the BSD open-source license, allowing it to be used in commercial and open-source projects with few restrictions.
Is Pyglet any good?
Pyglet is definitely faster out of the box than pygame, which is always a concern when developing with pygame (you have to update the smallest parts of the screen, and remembering what has changed can be tedious).
Conclusion
In this article, we saw the theoretical and practical implementation of pyglet.image in game development. We hope that this blog has helped you enhance your knowledge regarding pyglet.image in game development. If you would like to learn more about Pyglet Library, Why is Pyglet used, Asteroids game using Pyglet, and more, check out our articles on Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!