Core Library Definitions
The term_img.image
module defines the following:
- class term_img.image.TermImage(image, *, width=None, height=None, scale=(1.0, 1.0))
Bases:
object
Text-printable image
- Parameters
image (PIL.Image.Image) – Image to be rendered.
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
whenrender 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 original_size
Original image size
- property n_frames
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
whenrender 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.
Note
It’s not neccesary to explicity call this method, as it’s automatically called when neccesary.
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, *, animate=True, ignore_oversize=False)
Draws/Displays an image in the terminal, with optional alignment and padding.
- 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 (i.e black background).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.
animate (bool) – If
False
, disable animation i.e draw only the current frame of an animated image.ignore_oversize (bool) – If
True
, do not verify if the image will fit into the available terminal size with it’s currently set render size.
- Raises
TypeError – An argument is of an inappropriate type.
ValueError – An argument has an unexpected/invalid value.
ValueError – Render size or scale too small.
term_img.exceptions.InvalidSize – The terminal has been resized in such a way that the previously set size can no longer fit into it.
term_img.exceptions.InvalidSize – The image is animated and the previously set size won’t fit into the available terminal size.
- Return type
None
Note
Animations, if not disabled, are infinitely looped but can be terminated with
Ctrl-C
(SIGINT
or “KeyboardInterrupt”).If
set_size()
was previously used to set the render size (directly or not), the last values of its check_height, h_allow and v_allow parameters are taken into consideration, with check_height applying to only non-animated images.For animated images, when animate is
True
:Render size and padding height are always validated.
ignore_oversize has no effect.
- 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
TypeError – filepath 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
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
TypeError – url 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
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, check_width=True, check_height=True)
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.check_width (bool) – If
False
, the validity of the resulting rendered width is not checked.check_height (bool) – If
False
, the validity of the resulting rendered height is not checked.
- Raises
TypeError – An argument is of an inappropriate type.
ValueError – An argument has an unexpected/invalid value but of an appropriate type.
ValueError – Both width and height are specified.
ValueError – The available size is too small.
term_img.exceptions.InvalidSize – The resulting render size is too small.
term_img.exceptions.InvalidSize – The resulting rendered size will not fit into the available terminal size (or maxsize, if given).
- Return type
None
If neither width nor height is given or anyone given is
None
:and check_height and check_width are both
True
, the size is automatically calculated to fit within the available terminal size (or maxsize, if given).and check_height is
False
, the size is set such that the rendered width is exactly the available terminal width ormaxsize[0]
(assuming the render scale equals 1), regardless of the font ratio.and check_width is
False
(and check_height isTrue
), the size is set such that the rendered height is exactly the available terminal height ormaxsize[1]
(assuming the render scale equals 1), regardless of the font ratio.
Allowance does not apply when maxsize is given.
No vertical allowance when check_height isFalse
.No horizontal allowance when check_width isFalse
.The check_height might be set to
False
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.All image rendering and formatting methods recognize and respect the check_height, h_allow and v_allow options, until the size is re-set or unset.
check_width 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.
- tell()
Returns the current image frame number.
- Return type
int
Note
It’s allowed to set properties for animated images on non-animated ones, the values are simply ignored.
Context Manager Support
TermImage
instances are context managers i.e they can be used with the with
statement such as in:
with TermImage.from_url(url) as image:
...
Using an instance as a context manager ensures 100% guarantee to of object finalization (i.e clean-up/release of resources), especially for instances with URL sources (see TermImage.from_url()
).