Core Library Definitions

The term_image.image module defines the following:

Note

It’s allowed to set properties for animated images on non-animated ones, the values are simply ignored.

class term_image.image.TermImage(image, *, width=None, height=None, scale=(1.0, 1.0))

Bases: object

Text-printable image

Parameters
  • image (Image.Image) – Source image.

  • width (Optional[int]) – Horizontal dimension of the image, in columns.

  • height (Optional[int]) – Vertical dimension of the image, in lines.

  • scale (Tuple[float, float]) – The fraction of the size on respective axes, to render the image with.

Raises
  • TypeError – An argument is of an inappropriate type.

  • ValueError – An argument has an unexpected/invalid value.

Return type

None

Propagates exceptions raised by set_size(), if width or height is given.

Note

  • width or height is the exact number of columns or lines that’ll be used to draw the image (assuming the scale equal 1), regardless of the currently set font ratio.

  • If neither is given or both are None, the size is automatically determined when the image is to be rendered, such that it optimally fits into the terminal.

  • The image size is multiplied by the scale on respective axes before the image is rendered.

property closed

Instance finalization status

property frame_duration

Duration (in seconds) of a single frame for animated images

Setting this on non-animated images is simply ignored, no exception is raised.

property height

The unscaled height of the image.

None when the image size is unset.

Settable values:

  • None: Sets the image size to an automatically calculated one, based on the current terminal size.

  • A positive int: Sets the image height to the given value and the width proportionally.

property is_animated

True if the image is animated. Otherwise, False.

property original_size

Size of the source image (in pixels)

property n_frames: int

The number of frames in the image

property rendered_height

The scaled height of the image.

Also the exact number of lines that the drawn image will occupy in a terminal.

property rendered_size

The scaled size of the image.

Also the exact number of columns and lines (respectively) that the drawn image will occupy in a terminal.

property rendered_width

The scaled width of the image.

Also the exact number of columns that the drawn image will occupy in a terminal.

property scale

Image scale

Settable values are:

  • A scale value; sets both axes.

  • A tuple of two scale values; sets (x, y) respectively.

A scale value is a float in the range 0.0 < value <= 1.0.

property scale_x

Horizontal scale

A scale value is a float in the range 0.0 < x <= 1.0.

property scale_y

Vertical scale

A scale value is a float in the range 0.0 < y <= 1.0.

property size

The unscaled size of the image.

None when the image size is unset.

Setting this to None unsets the image size (so that it’s automatically calculated whenever the image is rendered) and resets the recognized advanced sizing options to their defaults.

This is multiplied by the scale on respective axes before the image is rendered.

property source

The source from which the instance was initialized

Can be a PIL image, file path or URL.

property width

The unscaled width of the image.

None when the image size is unset.

Settable values:

  • None: Sets the image size to an automatically calculated one, based on the current terminal size.

  • A positive int: Sets the image width to the given value and the height proportionally.

close()

Finalizes the instance and releases external resources.

  • In most cases, it’s not neccesary to explicity call this method, as it’s automatically called when the instance is garbage-collected.

  • This method can be safely called mutiple times.

  • If the instance was initialized with a PIL image, the PIL image is never finalized.

Return type

None

draw(h_align=None, pad_width=None, v_align=None, pad_height=None, alpha=0.1568627450980392, *, scroll=False, animate=True, repeat=- 1, cached=100, check_size=True)

Draws/Displays an image in the terminal.

Parameters
  • h_align (Optional[str]) – Horizontal alignment (“left” / “<”, “center” / “|” or “right” / “>”). Default: center.

  • pad_width (Optional[int]) –

    Number of columns within which to align the image.

    • Excess columns are filled with spaces.

    • Must not be greater than the available terminal width.

    • Default: terminal width, minus horizontal allowance.

  • v_align (Optional[str]) – Vertical alignment (“top”/”^”, “middle”/”-” or “bottom”/”_”). Default: middle.

  • pad_height (Optional[int]) –

    Number of lines within which to align the image.

    • Excess lines are filled with spaces.

    • Must not be greater than the available terminal height, for animations.

    • Default: terminal height, minus vertical allowance.

  • alpha (Optional[float]) –

    Transparency setting.

    • If None, transparency is disabled (uses the image’s default background color).

    • If a float (0.0 <= x < 1.0), specifies the alpha ratio above which pixels are taken as opaque.

    • If a string, specifies a hex color with which transparent background should be replaced.

  • scroll (bool) –

    Only applies to non-animations. If True:

  • animate (bool) – If False, disable animation i.e draw only the current frame of an animated image.

  • repeat (int) – The number of times to go over all frames of an animated image. A negative value implies infinite repetition.

  • cached (Union[bool, int]) –

    Determines if rendered frames of an animated image will be cached (for speed up of subsequent renders of the same frame) or not.

    • If bool, it directly sets if the frames will be cached or not.

    • If int, caching is enabled only if the framecount of the image is less than or equal to the given number.

  • check_size (bool) – If False, does not perform size validation for non-animations.

Raises
Return type

None

  • If set_size() was directly used to set the image size, the values of the fit_to_width, h_allow and v_allow arguments (when set_size() was called) are taken into consideration during size validation, with fit_to_width applying to only non-animations.

  • If the size was set via another means or the size is unset, the default values of those parameters are used.

  • If the image size was set with the fit_to_width parameter of set_size() set to True, then setting scroll is unnecessary.

  • animate, repeat and cached apply to animated images only. They are simply ignored for non-animated images.

  • For animations (i.e animated images with animate set to True):

    • scroll is ignored.

    • Image size and padding height are always validated, if set or given.

  • Animations, by default, are infinitely looped and can be terminated with Ctrl-C (SIGINT), raising KeyboardInterrupt.

classmethod from_file(filepath, **kwargs)

Creates a TermImage instance from an image file.

Parameters
  • filepath (str) – Relative/Absolute path to an image file.

  • kwargs (Union[None, int, Tuple[float, float]]) – Same keyword arguments as the class constructor.

Returns

A new TermImage instance.

Raises
  • TypeErrorfilepath is not a string.

  • FileNotFoundError – The given path does not exist.

  • IsADirectoryError – Propagated from from PIL.Image.open().

  • UnidentifiedImageError – Propagated from from PIL.Image.open().

Return type

term_image.image.TermImage

Also Propagates exceptions raised or propagated by the class constructor.

classmethod from_url(url, **kwargs)

Creates a TermImage instance from an image URL.

Parameters
  • url (str) – URL of an image file.

  • kwargs (Union[None, int, Tuple[float, float]]) – Same keyword arguments as the class constructor.

Returns

A new TermImage instance.

Raises
  • TypeErrorurl is not a string.

  • ValueError – The URL is invalid.

  • term_image.exceptions.URLNotFoundError – The URL does not exist.

  • PIL.UnidentifiedImageError – Propagated from PIL.Image.open().

Return type

term_image.image.TermImage

Also propagates connection-related exceptions from requests.get() and exceptions raised or propagated by the class constructor.

Note

This method creates a temporary image file, but only after a successful initialization.

Proper clean-up is guaranteed except maybe in very rare cases.

To ensure 100% guarantee of clean-up, use the object as a context manager.

seek(pos)

Changes current image frame.

Parameters

pos (int) – New frame number.

Raises
  • TypeError – An argument is of an inappropriate type.

  • ValueError – An argument has an unexpected/invalid value but of an appropriate type.

Return type

None

Frame numbers start from 0 (zero).

set_size(width=None, height=None, h_allow=0, v_allow=2, *, maxsize=None, fit_to_width=False, fit_to_height=False)

Sets the image size with extended control.

Parameters
  • width (Optional[int]) – Horizontal dimension of the image, in columns.

  • height (Optional[int]) – Vertical dimension of the image, in lines.

  • h_allow (int) – Horizontal allowance i.e minimum number of columns to leave unused.

  • v_allow (int) – Vertical allowance i.e minimum number of lines to leave unused.

  • maxsize (Optional[Tuple[int, int]]) – If given, as (columns, lines), it’s used instead of the terminal size.

  • fit_to_width (bool) – Only used with automatic sizing. See description below.

  • fit_to_height (bool) – Only used with automatic sizing. See description below.

Raises
  • TypeError – An argument is of an inappropriate type.

  • ValueError – An argument is of an appropriate type but has an unexpected/invalid value.

  • ValueError – Both width and height are specified.

  • ValueErrorfit_to_width or fit_to_height is True when width, height or maxsize is given.

  • ValueError – The available size is too small for automatic sizing.

  • term_image.exceptions.InvalidSizemaxsize is given and the resulting size will not fit into it.

Return type

None

If neither width nor height is given or anyone given is None, automatic sizing applies. In such a case, if:

Important

  1. fit_to_width and fit_to_height are mutually exclusive. Only one can be True at a time.

  2. Neither fit_to_width nor fit_to_height may be True when width, height or maxsize is given.

  3. Be careful when setting fit_to_height to True as it might result in the image’s rendered width being larger than the terminal width (or maxsize[0]) because draw() will (by default) raise term_image.exceptions.InvalidSize if such is the case.

Vertical allowance does not apply when fit_to_width is True.
horizontal allowance does not apply when fit_to_height is True.

Allowances are ignored when maxsize is given.

fit_to_width might be set to True to set the image size for vertically-oriented images (i.e images with height > width) such that the drawn image spans more columns but the terminal window has to be scrolled to view the entire image.

Image formatting and all size validation recognize and respect the values of the fit_to_width, h_allow and v_allow parameters, until the size is re-set or unset.

fit_to_height is only provided for completeness, it should probably be used only when the image will not be drawn to the current terminal. The value of this parameter is not recognized by any other method or operation.

Note

The size is checked to fit in only when maxsize is given along with width or height because draw() is generally not the means of drawing such an image and all rendering methods don’t perform any sort of size validation.

If the validation is not desired, specify only one of maxsize and width or height, not both.

tell()

Returns the current image frame number.

Return type

int

class term_image.image.ImageIterator(image, repeat=- 1, format='', cached=100)

Bases: object

Effeciently iterate over rendered frames of an animated image

Parameters
  • image (TermImage) – Animated image.

  • repeat (int) – The number of times to go over the entire image. A negative value implies infinite repetition.

  • format (str) – The format specification to be used to format the rendered frames (default: auto).

  • cached (Union[bool, int]) –

    Determines if the rendered frames will be cached (for speed up of subsequent renders) or not.

    • If bool, it directly sets if the frames will be cached or not.

    • If int, caching is enabled only if the framecount of the image is less than or equal to the given number.

Return type

None

  • If repeat equals 1, caching is disabled.

  • The iterator has immediate response to changes in the image size and scale.

  • If the image size is unset, it’s automatically calculated per frame.

  • The current frame number reflects on the underlying image during iteration.

  • After the iterator is exhausted, the underlying image is set to frame 0.

close()

Closes the iterator and releases resources used.

Does not reset the frame number of the underlying image.

Note

This methods is automatically called when the iterator is exhausted or garbage-collected.

Return type

None


Context Management Protocol Support

TermImage instances are context managers i.e they can be used with the with statement as in:

with TermImage.from_url(url) as image:
    ...

Using an instance as a context manager more surely guarantees object finalization (i.e clean-up/release of resources), especially for instances with URL sources (see TermImage.from_url()).

Iteration Support

Animated TermImage instances are iterable i.e they can be used with the for statement (and other means of iteration such as unpacking) as in:

for frame in TermImage.from_file("animated.gif"):
    ...

Subsequent frames of the image are yielded on subsequent iterations.

Note

  • iter(anim_image) returns an ImageIterator instance with a repeat count of 1, hence caching is disabled.

  • The frames are unformatted and transparency is enabled i.e as returned by str(image).

For more extensive or custom iteration, use ImageIterator directly.