Image

Martin McBride, 2021-01-01
Tags geometry image
Categories generativepy generative art

generativepy has moved to the pythoninformer.com website, and this page might not be up to date. Please visit the new location.

The Image class renders an image on a drawing context.

This is intended for very simple display of images:

• The image must be available as a PNG file.
• The full image will be rendered as a rectangle, the same size as the original image.
• The image can optionally be scaled by a factor.

The rendered image size in user space units will match the pixel size of the original PNG image.

The image can be transformed using standard PyCairo context calls, so you can rotate, mirror, stretch or shear the image. You can also apply a clip path prior to rendering the image, to change its shape. Transparent PNG images are supported.

Image class methods

The Image is not derived for Shape, so it doesn't inherit any of its methods.

It has the following methods:

• of_file_position
• scale
• paint

Constructor

The Image constructor accepts a context object (similar to Shape objects):

Image(ctx)


of_file_position

Specifies an image file and a position.

of_file_position(filename, position)

Parameter Type Description
filename string The file path of a PNG file contianing the image.
position (number, number) A tuple of two numbers, giving the (x, y) position of the top left corner of the image.

By default, the image will be rendered with its top left corner at position. If user space is mirrored or rotated, it may appear differently on the page.

scale

Sets the image scale factor.

scale(factor)

Parameter Type Description
scale number The scale factor for the image

Scales the image by a factor. For example, a factor of 2 will make the image appear twice as big on the page.

If this function is not called, a scale factor of 1 is used by default.

paint

Renders the image.

paint()


Example

Here is some example code that draws an image on the page. The same image is drawn twice, once at normal size and once scaled to half size. The full code can be found on github. The code assumes there is an image cat.png in the current folder:

from generativepy.drawing import make_image, setup
from generativepy.color import Color
from generativepy.geometry import Image

'''
Draw an image
'''

def draw(ctx, width, height, frame_no, frame_count):
setup(ctx, width, height, width=500, background=Color(0.8))

Image(ctx).of_file_position('cat.png', (50, 50)).paint()
Image(ctx).of_file_position('cat.png', (300, 50)).scale(0.5).paint()

make_image("/tmp/geometry-image.png", draw, 400, 200)


Here is the result: