Core Library Definitions

The term_img.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_img.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]) – The width to render the image with.

  • height (Optional[int]) – The height to render the image with.

  • scale (Tuple[float, float]) – The image render scale on respective axes.

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

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

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

Note

  • width is not neccesarily the exact number of columns that’ll be used to render the image. That is influenced by the currently set font ratio.

  • height is 2 times the number of lines that’ll be used in the terminal.

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

  • The size is multiplied by the scale on each axis respectively 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

Image render height

None when render size is unset.

Settable values:

  • None: Sets the render size to the automatically calculated one.

  • A positive int: Sets the render height to the given value and the width proprtionally.

The image is actually rendered using half this number of lines

property is_animated

True if the image is animated. Otherwise, False.

property original_size

Original image size in pixels

property n_frames: int

The number of frames in the image

property rendered_height

The number of lines that the drawn image will occupy in a terminal

property rendered_size: Tuple[int, int]

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

property rendered_width

The number of columns that the drawn image will occupy in a terminal

property scale

Image render 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

x-axis render scale

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

property scale_y

y-ayis render scale

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

property size

Image render size

None when render size is unset.

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

property source

The source from which the instance was initialized

Can be a PIL image, file path or URL.

property width

Image render width

None when render size is unset.

Settable values:

  • None: Sets the render size to the automatically calculated one.

  • A positive int: Sets the render 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.

    • default: terminal width.

  • 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.

    • default: terminal height, with a 2-line 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

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

  • If set_size() was previously used to set the render size (directly or not), the last values of its fit_to_width, h_allow and v_allow parameters are taken into consideration, with fit_to_width applying to only non-animations.

  • If the render size was set with the fit_to_width paramter 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):

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[int, None, 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_img.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[int, None, 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_img.exceptions.URLNotFoundError – The URL does not exist.

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

Return type

term_img.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 render size with advanced control.

Parameters
  • width (Optional[int]) – Render width to use.

  • height (Optional[int]) – Render height to use.

  • 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 (cols, 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_img.exceptions.InvalidSize – The resulting render size is too small.

  • term_img.exceptions.InvalidSizemaxsize is given and the resulting rendered 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_img.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 render 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 because draw() is generally not the means of drawing such an image and all rendering methods don’t perform any sort of render size validation.

tell()

Returns the current image frame number.

Return type

int

class term_img.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.

  • If repeat equals 1, caching is disabled.

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

  • If the render 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.


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.