Images

Opening and Creating Images

imlib2.open(filename, size=None)

Decode an image from disk.

Parameters:
  • filename (str) – path to the file to open
  • size (2-tuple of ints) – initial width and height of the image; if either dimension is -1, it will be computed based on aspect ratio; if size is None, use the default image size.
Returns:

Image object

kaa.imlib2 (unlike Imlib2 natively) supports rasterization of SVG images. however detection is based on file extension. If you need to rasterize an SVG file that doesn’t have a .svg extension, you will need to use open_from_memory().

For non-SVG images, this function will cache the raw image data of the loaded file, so that subsequent invocations with the given filename will load from cache.

>>> from kaa import imlib2
>>> imlib2.open('file.jpg')
<kaa.imlib2.Image object size=1920x1080 0x9347eac>
# SVGs can be loaded the same way.
>>> imlib2.open('image.svg', size=(640, -1))
<kaa.imlib2.Image object size=640x371 at 0xb69df84c>
imlib2.open_without_cache(filename, size=None)

Decode an image from disk without looking in the cache (or storing the result in the cache).

Parameters:
  • filename (str) – path to the file to open
  • size (2-tuple of ints) – initial width and height of the image; if either dimension is -1, it will be computed based on aspect ratio; if size is None, use the default image size.
Returns:

Image object

imlib2.open_from_memory(buf, size=None)

Decode an image stored in memory.

Parameters:
  • buf (str or buffer) – encoded image data
  • size (2-tuple of ints) – initial width and height of the image; if either dimension is -1, it will be computed based on aspect ratio; if size is None, use the default image size.
Returns:

Image object

Note

Due to limitations in Imlib2, this function uses POSIX shared memory if it’s available (such as on Linux). If it’s not available, a temporary file will be created in /tmp.

>>> from kaa import imlib2
# This example is a bit contrived because you could easily use open(), but
# shows that if you have an existing buffer with encoded image data, you
# can use this function to decode it into an Image object.
>>> data = file('file.jpg').read()
>>> imlib2.open_from_memory(data)
<kaa.imlib2.Image object size=1920x1080 0x9347eac>
imlib2.new(size, bytes=None, from_format='BGRA', copy=True)

Create a new Image object (optionally) from existing raw data.

Parameters:
  • size (2-tuple of ints) – width and height of the image to create
  • bytes (str, buffer, int, None) – raw image data from which to initialize the image, which must be in the RGB colorspace; if an int, specifies a pointer to a location in memory holding the raw image (default: None)
  • from_format (str) – specifies the pixel format of the supplied raw data; can be any permutation of RGB or RGBA. (default: BGRA, which is Imlib2’s native pixel format).
  • copy (bool) – if True, the raw data bytes will be copied to the Imlib2 object. If False, bytes must be either a writable buffer or an integer pointing to a location in memory; in this case, if from_format is BGRA then Imlib2 will directly use the supplied buffer; if it’s not BGRA then a colorspace conversion is necessary, but an in-place conversion will be done if possible.
Returns:

Image object

bytes can be an integer, acting as a pointer to memory, which is useful with interoperating with other libraries, however this should be used with extreme care as incorrect values can segfault the interpeter.

Warning

Formats (e.g. BGRA) indicate the byte order when the image is viewed as a memory buffer on little-endian machines. Each pixel is a 32-bit quantity where blue is stored in the least significant byte and alpha is the most significant byte. On big-endian architectures, the format BGRA is actually stored in the order ARGB.

>>> from kaa import imlib2
# Create a new, blank 1920x1080 image.
>>> imlib2.new((1920, 1080))
<kaa.imlib2.Image object size=1920x1080 at 0x9c0dbec>
# Create a new 1024x768 image initialized from existing data (all pixels
# 50% opaque red)
>>> imlib2.new((1024, 768), bytes='\x00\x00\xff\x7f' * 1024 * 768)
<kaa.imlib2.Image object size=1024x768 at 0x9c79d4c>
# Create a new 1024x768 image initialized from 24-bit data whose pixel
# order is RGB.  (Alpha channel is initialized to 255)
>>> imlib2.new((1024, 768), bytes='\xff\x00\x00' * 1024 * 768, from_format='RGB')
<kaa.imlib2.Image object size=1024x768 at 0x9c79dec>

The following code shows how you can use the array type to share a writable buffer:

>>> import array
# Initialize an array with 50% opaque purple.
>>> data = array.array('c', '\xff\x00\xff\x7f' * 1024 * 768)
# Create the image with copy=False so we share the buffer.
>>> img = imlib2.new((1024, 768), data, copy=False)
# Note the value of the first pixel.
>>> data[:4]
array('c', '\xff\x00\xff\x7f')
# Clear the image and look at the same pixel, note how it's changed in the
# buffer.
>>> img.clear()
>>> data[:4]
array('c', '\x00\x00\x00\x00')

Although you can use writable buffers directly as in the above example, you can also pass a integer which represents a pointer to the buffer.

>>> data = array.array('c', '\xff\x00\xff\x7f' * 1024 * 768)
>>> ptr, len = data.buffer_info()
>>> ptr
3022487560L
>>> img = imlib2.new((1024, 768), ptr, copy=False)
>>> img.clear()
>>> data[:4]
array('c', '\x00\x00\x00\x00')

You would never actually do this for arrays, but if you have a pointer to a buffer returned by some other library (gotten through ctypes, perhaps), you can use the pointer as a buffer. In this case, you maintain ownership over the buffer, and it is your responsibility to free it.

Image Cache

imlib2.set_cache_size(size)

Sets the size of Imlib2’s internal image cache.

Parameter:size (int) – size in bytes; a value of 0 will flush the cache and prevent future caching.

When the cache size is set, Imlib2 will flush old images from the cache until the current cache usage is less than or equal to the cache size.

Note

The cache size is initialized to 4MB.

imlib2.get_cache_size()

Return the size of Imlib2’s internal image cache.

Returns:size in bytes of the cache

Image Objects

class imlib2.Image(image_or_filename, use_cache=True, size=None)

Image class representing an Imlib2 Image object.

Parameters:
  • image_or_filename (Image or str) – another Image object to clone, or a filename of the encoded image to load on disk.
  • use_cache (bool) – if True, will use Imlib2’s internal cache for image data

It is possible to create Image objects directly, but the imlib2.open() or imlib2.new() module functions are more likely to be useful.

Synopsis

Class Hierarchy

kaa.Object
└─ imlib2.Image

Methods
as_gdk_pixbuf()Convert the image into a gdk.Pixbuf object.
blend()Blend the supplied image onto the current image.
blur()Blur the image in-place.
clear()Clear the specified rectangle, resetting all pixels in that rectangle to fully transparent (#0000).
copy()Create a copy of the current image.
copy_rect()Copy a region within the image.
crop()Crop the image and return a new image.
draw_ellipse()Draw an ellipse (filled or outline) on the image.
draw_mask()Apply the luma channel of another image to the alpha channel of the current image.
draw_rectangle()Draw a rectangle (filled or outline) on the image.
draw_text()Draw text on the image, optionally stylized.
flip_diagonal()Flip the image on along its diagonal, so that the top-right corner is mapped to the bottom left.
flip_horizontal()Flip the image horizontally (along its vertical axis).
flip_vertical()Flip the image vertically (along its horizontal axis).
get_font()Deprecated: use the font property instead.
get_pixel()Fetch the RGBA value of a specifix pixel.
get_raw_data()Return the underlying raw data of the image.
orientate()Perform in-place 90 degree rotations on the image.
put_back_raw_data()Put back the writable buffer that was obtained with get_raw_data().
rotate()Rotate the image and return a new image.
save()Save the image to a file.
scale()Scale the image and return a new image.
scale_preserve_aspect()Scale the image while preserving the original aspect ratio and return a new image.
set_alpha()Deprecated: use set_has_alpha() instead.
set_font()Deprecated: use the font property instead.
set_has_alpha()Enable or disable the alpha channel.
sharpen()Sharpen the image in-place.
thumbnail()Scale the image in-place, preserving the original aspect ratio.
Properties
filenameread-onlyThe filename of the image if lodaed from a file, None otherwise.
fontread/writeFont object specifying font context used by draw_text(), or None if no font was set.
formatread-onlyThe encoded format (e.g. ‘png’, ‘jpeg’) of the image if loaded from a file, None otherwise.
has_alpharead-onlyTrue if the image has an alpha channel, False otherwise.
heightread-onlyThe height of the image in pixels.
moderead-onlyThe pixel format of the decoded image in memory (always BGRA).
rowstrideread-onlyThe number of bytes each row of pixels occupies in memory.
sizeread-onlyA 2-tuple of the width and height of the image in pixels.
widthread-onlyThe width of the image in pixels.
Signals
changedEmitted when the image has been altered in some way.

Methods

as_gdk_pixbuf()

Convert the image into a gdk.Pixbuf object.

Raises:ImportError if pygtk is not available.
Returns:a gdk.Pixbuf object containing a copy of the image data
>>> from kaa import imlib2
>>> img = imlib2.open('file.png')
>>> img.as_gdk_pixbuf()
<gtk.gdk.Pixbuf object at 0x909334c (GdkPixbuf at 0x9452318)>
blend(src, src_pos=(0, 0), src_size=(-1, -1), dst_pos=(0, 0), dst_size=(-1, -1), alpha=255, merge_alpha=True)

Blend the supplied image onto the current image.

Parameters:
  • src (Image object) – the image being blended onto ‘self’
  • dst_pos (2-tuple of ints) – the x, y coordinates where the source image will be blended onto the destination image
  • src_pos (2-tuple of ints) – the x, y coordinates within the source image where blending will start.
  • src_size (2-tuple of ints) – the width and height of the source image to be blended. A value of -1 for either one indicates the full dimension of the source image.
  • alpha (int) – the “layer” alpha that is applied to all pixels of the image. If an individual pixel has an alpha of 128 and this value is 128, the resulting pixel will have an alpha of 64 before it is blended to the destination image. 0 is fully transparent and 255 is fully opaque, and 256 is a special value that means alpha blending is disabled.
  • merge_alpha (bool) – if True, the alpha channel is also blended. If False, the destination image’s alpha channel is untouched and the RGB values are compensated.
Returns:

self

This example overlays an image called a.jpg, rotated 20 degrees and 60% opaque, onto an image called b.jpg at 50, 50.

>>> from kaa import imlib2
>>> img = imlib2.open('b.jpg')
>>> img.blend(imlib2.open('a.jpg').rotate(20), dst_pos=(50, 50), alpha=60)

Calling this method will emit the changed signal.

blur(radius)

Blur the image in-place.

Parameter:radius (int) – the size of the blur matrix radius (higher values produce more blur)
Returns:self

Calling this method will emit the changed signal.

clear(pos=(0, 0), size=(0, 0))

Clear the specified rectangle, resetting all pixels in that rectangle to fully transparent (#0000).

Parameters:
  • pos (2-tuple of ints) – left/top corner of the rectangle
  • size (2-tuple of ints) – width and height of the rectangle; if either value is less than or equal to zero then they are relatve to the far edge of the image
Returns:

self

If this method is called without arguments, the whole image will be cleared.

Calling this method will emit the changed signal.

copy()

Create a copy of the current image.

Returns:a new Image object, copied from the current image.

Note

Any callbacks connected to the changed signal will not be preserved in the copy.

copy_rect(src_pos, size, dst_pos)

Copy a region within the image.

Parameters:
  • src_pos (2-tuple of ints) – the x, y coordinates marking the top left of the region to be moved.
  • size (2-tuple of ints) – the width and height of the region to move. If either dimension is -1, then that dimension extends to the far edge of the image.
  • dst_pos (2-tuple of ints) – the x, y coordinates within the image where the region will be moved to.
Returns:

self

Calling this method will emit the changed signal.

crop((x, y), (w, h))

Crop the image and return a new image.

Parameters:
  • x, y (int) – left/top offset of cropped image
  • w, h (int) – width and height of the cropped image (offset at x); values less than or equal to zero are relative to the far edge of the image.
Returns:

a new Image object

>>> from kaa import imlib2
>>> img = imlib2.open('file.jpg')
>>> img
<kaa.imlib2.Image object size=1920x1080 at 0xb73cef6c>
>>> img.crop((100, 100), (-100, -100))
<kaa.imlib2.Image object size=1720x880 at 0x8a73f4c>
draw_ellipse((xc, yc), (a, b), color, fill=True)

Draw an ellipse (filled or outline) on the image.

Parameters:
  • xc, yc – the x, y coordinates of the center of the ellipse
  • a, b (int) – the horizontal and veritcal amplitude of the ellipse
  • color – any value supported by imlib2.normalize_color()
  • fill – True if the ellipse should be filled, False if outlined
Returns:

self

Calling this method will emit the changed signal.

draw_mask(maskimg, pos=(0, 0))

Apply the luma channel of another image to the alpha channel of the current image.

Parameters:
  • maskimg (Image object) – the image from which to read the luma channel
  • pos – the left/top coordinates within the current image where the alpha channel will be modified. The mask is drawn to the full width/height of maskimg.
Returns:

self

This example creates a mask for an image with three vertical strips of different shades of white. Once the mask is drawn to the image, the image will have three strips of different alpha values: 100% (255), 73% (187), and 53% (136).

>>> from kaa import imlib2
>>> img = imlib2.open('file.jpg')
>>> mask = imlib2.new(img.size)
>>> mask.draw_rectangle((0, 0), (img.width/3, img.height), color='#ffffff')
>>> mask.draw_rectangle((img.width/3, 0), (img.width/3, img.height), color='#bbbbbb')
>>> mask.draw_rectangle((img.width/3*2, 0), (img.width/3, img.height), color='#888888')
>>> img.draw_mask(mask)

Calling this method will emit the changed signal.

draw_rectangle((x, y), (w, h), color, fill=True)

Draw a rectangle (filled or outline) on the image.

Parameters:
  • x, y (int) – the top left corner of the rectangle
  • w, h (int) – the width and height of the rectangle; values less than or equal to zero are relative to the far edge
  • color – any value supported by imlib2.normalize_color()
  • fill – True if the rectangle should be filled, False if outlined
Returns:

self

Calling this method will emit the changed signal.

draw_text((x, y), text, color=None, font_or_fontname=None, style=None, shadow=None, outline=None, glow=None, glow2=None)

Draw text on the image, optionally stylized.

Parameters:
  • x, y (int) – the left/top coordinates within the current image where the text will be rendered
  • text (str or unicode) – the text to be rendered
  • color (3- or 4-tuple of ints) – any value supported by imlib2.normalize_color(); if None, the color of the font context, as set by font property, is used.
  • font_or_fontname – Font object or ‘font/size’ (e.g. ‘arial/16’)
  • style (a TEXT_STYLE constant) – the style to use to draw the supplied text. If style is None, the style from the font object will be used.
Returns:

a 4-tuple representing the width, height, horizontal advance, and vertical advance of the rendered text.

>>> from kaa import imlib2
>>> imlib2.auto_set_font_path()
>>> img = imlib2.new((1920, 1080))
# Assumes VeraBd.ttf is in the font path.
>>> img.draw_text((100, 100), 'Hello World!', '#ff55ff', 'VeraBd/60',
...               style=imlib2.TEXT_STYLE_SOFT_SHADOW, shadow='#888888')
(557, 92, 557, 93)

Calling this method will emit the changed signal.

flip_diagonal()

Flip the image on along its diagonal, so that the top-right corner is mapped to the bottom left.

Returns:self

In practice:

>>> img.flip_diagonal()

is equivalent to (but a bit faster than):

>>> img.orientate(1).flip_horizontal()

Calling this method will emit the changed signal.

flip_horizontal()

Flip the image horizontally (along its vertical axis).

Returns:self

Calling this method will emit the changed signal.

flip_vertical()

Flip the image vertically (along its horizontal axis).

Returns:self

Calling this method will emit the changed signal.

get_font()
Deprecated: use the font property instead.
get_pixel((x, y))

Fetch the RGBA value of a specifix pixel.

Parameter:x, y (int) – the coordinate of the pixel
Returns:4-tuple of (red, green, blue, alpha) where each value is between 0 and 255.
get_raw_data(format='BGRA', write=False)

Return the underlying raw data of the image.

Parameters:
  • format (str) – the pixel format of the returned buffer; must be a permutation of RGB or RGBA (default: BGRA, Imlib2’s native pixel layout).
  • write (bool) – if True, the returned buffer will be writable.
Returns:

a read-only buffer (if write is False and format is BGRA) or a read-write buffer (if write is True or format is not BGRA)

When format is not BGRA (i.e. not Imlib2’s native buffer), pixel format conversion will be performed and the converted raw data copied to a newly allocated buffer. The returned buffer will therefore always be read-write. Writing to this buffer will have no effect on the image.

When format is BGRA, the returned buffer will map directly onto Imlib2’s underlying pixel buffer. In this case, the returned buffer will only be read-write if write is True, which will allow you to directly manipulate the underlying buffer. You must call put_back_raw_data() when you’re done writing to the buffer.

>>> from kaa import imlib2
>>> img = imlib2.open('file.jpg')
>>> buf = img.get_raw_data(write=True)
# Set first pixel to white.
>>> buf[:4] = '\xff' * 4
>>> img.put_back_raw_data(buf)

Warning

see imlib2.new() for more information on the pixel layout. When modifying the buffer directly, you must be aware of the endianness of the machine.

orientate(orientation)

Perform in-place 90 degree rotations on the image.

Parameter:orientation (int) – 0 = no rotation, 1 = rotate clockwise 90 degrees, 2 = rotate clockwise 180 degrees, 3 = rotate clockwise 270 degrees.
Returns:self

Calling this method will emit the changed signal.

put_back_raw_data(data)

Put back the writable buffer that was obtained with get_raw_data().

Parameter:data (buffer) – the read-write buffer that was gotten from get_raw_data()

Changes made directly to the buffer will not be reflected in the image until this method is called. If you modify the buffer again, you must call this method again (but you needn’t call get_raw_data() again).

Calling this method will emit the changed signal.

rotate(angle)

Rotate the image and return a new image.

Parameter:angle (float) – the angle in degrees to rotate
Returns:a new Image object

The new image will be sized to fit the full contents of the rotated image, and likely quite a bit larger than it needs to be.

>>> from kaa import imlib2
>>> img = imlib2.open('file.png')
>>> img.size
(1920, 1080)
>>> img.rotate(20).size
(2208, 2208)
save(filename, format=None)

Save the image to a file.

Parameters:
  • filename (str) – the output filename
  • format – the encoding format (jpeg, png, etc.); if None, will be derived from the filename extension.
Returns:

self

scale(size, src_pos=(0, 0), src_size=(-1, -1))

Scale the image and return a new image.

Parameters:
  • size (2-tuple of ints) – the width and height of scaled image; if either width or height is -1, that dimension is calculated from the other dimension while preserving the aspect ratio.
  • src_pos (2-tuple of ints) – offset within the source image which will correspond to position (0,0) in the scaled image.
  • src_size (2-tuple of ints) – the amount of width and height of the source image to include (scaled) in the new image; if either dimension is -1, it will extend to the right or bottom border.
Returns:

a new imlib2.Image object

scale_preserve_aspect((w, h))

Scale the image while preserving the original aspect ratio and return a new image.

Parameters:
  • w – the maximum width of the new image
  • w (int) – the maximum height of the new image
Returns:

a new Image object

The new image will be as large as possible, using w and h as the upper limits, while retaining the original aspect ratio.

set_alpha(has_alpha)
Deprecated: use set_has_alpha() instead.
set_font(font_or_font_name)
Deprecated: use the font property instead.
set_has_alpha(has_alpha)

Enable or disable the alpha channel.

Parameter:has_alpha (False) – True if the alpha channel should be considered, False if the image is the alpha channel should be ignored (and the image is fully opaque)

Calling this method will emit the changed signal.

sharpen(radius)

Sharpen the image in-place.

Parameter:radius (int) – the size of the sharpen radius (higher values produce greater sharpening)
Returns:self

Calling this method will emit the changed signal.

thumbnail((w, h))

Scale the image in-place, preserving the original aspect ratio.

Parameters:
  • w – the maximum width of the new image
  • w (int) – the maximum height of the new image
Returns:

self

This implements behaviour of the PIL function of the same name.

Calling this method will emit the changed signal.

Properties

filename
The filename of the image if lodaed from a file, None otherwise.
font

Font object specifying font context used by draw_text(), or None if no font was set.

>>> from kaa import imlib2
>>> imlib2.auto_set_font_path()
>>> img = imlib2.new((1920, 1080))
>>> img.font = imlib2.Font('VeraBd/60', '#ff55ff')
>>> img.font.set_style(imlib2.TEXT_STYLE_SOFT_SHADOW, shadow='#888888')
>>> img.draw_text((100, 100), 'Hello World!')
(557, 92, 557, 93)
format
The encoded format (e.g. ‘png’, ‘jpeg’) of the image if loaded from a file, None otherwise.
has_alpha

True if the image has an alpha channel, False otherwise.

This can be changed via the set_has_alpha() method rather than setting this property, because set_has_alpha() has a side-effect of emitting the changed signal.

height
The height of the image in pixels.
mode
The pixel format of the decoded image in memory (always BGRA).
rowstride

The number of bytes each row of pixels occupies in memory.

This is typically width * 4.

size
A 2-tuple of the width and height of the image in pixels.
width
The width of the image in pixels.

Signals

changed

Emitted when the image has been altered in some way.

def callback(...)

Utility Functions

imlib2.get_max_rectangle_size((w, h), (max_w, max_h))

Compute the largest rectangle that can fit within one given rectangle, while retaining the aspect ratio of the other given rectangle.

Parameters:
  • w, h (int) – the dimensions of the rectangle whose aspect ratio to preserve
  • max_w, max_h (int) – the maximum dimensions of the computed rectangle
Returns:

(width, height) of the bound, aspect-preserved rectangle

imlib2.normalize_color(code)

Convert an HTML-style color code or an RGB 3-tuple into a 4-tuple of integers.

Parameter:code (str or 3- or 4-tuple) – a color code in the form #rrggbbaa, #rrggbb, #rgba or #rgb, or a 3- or 4-tuple of integers specifying (red, green, blue, alpha).
Returns:a 4-tuple of integers from 0-255 representing red, green, blue and alpha channels; if alpha is not specified in the color code, 255 is assumed.

Table Of Contents

Previous topic

kaa.imlib2 — Image Processing Library

Next topic

Fonts

This Page