Welcome to Term-Image’s documentation!#
Attention
đźš§ Under Construction - There might be incompatible changes between minor versions of version zero!
If you want to use this library in a project while it’s still on version zero,
ensure you pin the dependency to a specific minor version e.g >=0.4,<0.5
.
On this note, you probably also want to switch to the specific documentation for the version you’re using (somewhere at the lower left corner of this page).
Contents#
Getting Started#
Installation#
Requirements#
Operating System: Unix / Linux / MacOS X / Windows (limited support, see the FAQs)
Python >= 3.7
A terminal emulator with any of the following:
support for the Kitty graphics protocol.
support for the iTerm2 inline image protocol.
full Unicode support and ANSI 24-bit color support
Plans to support a wider variety of terminal emulators are in motion (see Planned Features).
Steps#
The latest stable version can be installed from PyPI with:
pip install term-image
The development version can be installed with:
pip install git+https://github.com/AnonymouX47/term-image.git
Supported Terminal Emulators#
Some terminals emulators that have been tested to meet the requirements for at least one render style include:
libvte-based terminal emulators such as:
Gnome Terminal
Terminator
Tilix
Kitty
Konsole
iTerm2
WezTerm
Alacritty
Windows Terminal
MinTTY (on Windows)
Termux (on Android)
Note
If you’ve tested term-image
on any other terminal emulator that meets all
requirements, please mention the name in a new thread under this discussion.
Also, if you’re having an issue with terminal support, you may report or check information about it in the discussion linked above.
Note
Some terminal emulators support 24-bit color escape sequences but have a 256-color pallete. This will limit color reproduction.
Tutorial#
This is a basic introduction to using the library. Please refer to the API Reference for detailed description of the features and functionality provided by the library.
For this tutorial we’ll be using the image below:

The image has a resolution of 288x288 pixels.
Note
All the samples in this tutorial occurred in a terminal window of 255 columns by 70 lines.
Creating an Instance#
Image instances can be created using the convenience functions AutoImage()
,
from_file()
and from_url()
,
which automatically detect the best style supported by the terminal emulator.
Instances can also be created using the Image Classes directly via their respective
constructors or from_file()
and
from_url()
methods.
Initialize with a file path:
from term_image.image import from_file image = from_file("path/to/python.png")
Initialize with a URL:
from term_image.image import from_url image = from_url("https://raw.githubusercontent.com/AnonymouX47/term-image/main/docs/source/resources/tutorial/python.png")
Initialize with a PIL (Pillow) image instance:
from PIL import Image from term_image.image import AutoImage img = Image.open("path/to/python.png") image = AutoImage(img)
Rendering an Image#
Rendering an image is the process of converting it (per-frame for animated images) into text (a string) which reproduces a representation or approximation of the image when written to the terminal.
Hint
To display the rendered image in the following steps, pass the string as an argument to print()
.
There are two ways to render an image:
Unformatted Rendering#
This is done using:
str(image)
The image is rendered without padding/alignment and with transparency enabled.
The output (using print()
) should look like:

Formatted Rendering#
Note
To see the effect of alignment in the steps below, set the image size smaller than your terminal size, with e.g:
image.height = 50
This sets the image height to 50
lines (which is less than 70
, the height of
the terminal window used to prepare this tutorial) and the width proportionally.
We’ll see more about this later.
Below are examples of formatted rendering:
format(image, "|200.^70#ffffff")
Renders the image with:
center horizontal alignment
a padding width of 200 columns
a padding height of 70 lines
white (
#ffffff
) background underlay
Note
You might have to reduce the padding width (200) and/or height (70) to something that’ll fit into your terminal window, or increase the size of the terminlal window
The output (using print()
) should look like:

f"{image:>._#.5}"
Renders the image with:
right horizontal alignment
default padding width (the current terminal width)
bottom vertical alignment
default padding height (the current terminal height minus two (
2
))transparent background with 0.5 alpha threshold
The output (using print()
) should look like:

"{:1.1#}".format(image)
Renders the image with:
center horizontal alignment (default)
no horizontal padding, since
1
is less than or equal to the image widthmiddle vertical alignment (default)
no vertical padding, since
1
is less than or equal to the image heighttransparency is disabled (alpha channel is ignored)
The output (using print()
) should look like:

See also
Drawing/Displaying an Image#
There are two basic ways to draw an image to the terminal screen:
Using the
draw()
method:image.draw()
NOTE:
draw()
has various parameters for Render Formatting.Using
print()
with an image render output (i.e printing the rendered string):print(image) # Uses str() # OR print(f"{image:>200.^70#ffffff}") # Uses format()
Note
Image Size#
The size of an image can be in either of two states:
Fixed
In this state,
the
size
property evaluates to a 2-tuple of integers, while thewidth
andheight
properties evaluate to integers,the image is rendered with the set size.
Dynamic
In this state,
the
size
,width
andheight
properties evaluate to aSize
enum member,the size with which the image is rendered is automatically calculated (based on the current terminal size or the image’s original size) whenever the image is to be rendered.
The size of an image can be set at instantiation by passing an integer or a
Size
enum member to either the width or the
height keyword-only parameter.
For whichever axis a dimension is given, the dimension on the other axis is calculated
proportionally.
Note
The arguments can only be given by keyword.
If neither is given, the
FIT
dynamic size applies.All methods of instantiation accept these arguments.
For example:
>>> from term_image.image import Size, from_file
>>> image = from_file("python.png") # Dynamic FIT
>>> image.size is Size.FIT
True
>>> image = from_file("python.png", width=60) # Fixed
>>> image.size
(60, 30)
>>> image.height
30
>>> image = from_file("python.png", height=56) # Fixed
>>> image.size
(112, 56)
>>> image.width
112
>>> image = from_file("python.png", height=Size.FIT) # Fixed FIT
>>> image.size
(136, 68)
>>> image = from_file("python.png", width=Size.FIT_TO_WIDTH) # Fixed FIT_TO_WIDTH
>>> image.size
(255, 128)
>>> image = from_file("python.png", height=Size.ORIGINAL) # Fixed ORIGINAL
>>> image.size
(288, 144)
No size validation is performed i.e the resulting size might not fit into the terminal window
>>> image = from_file("python.png", height=68) # Will fit in, OK
>>> image.size
(136, 68)
>>> image = from_file("python.png", height=500) # Will not fit in, also OK
>>> image.size
(1000, 500)
An exception is raised when both width and height are given.
>>> image = from_file("python.png", width=100, height=100)
Traceback (most recent call last):
.
.
.
ValueError: Cannot specify both width and height
The width
and height
properties can be used to set the size of an image after instantiation, resulting in fixed size.
>>> image = from_file("python.png")
>>> image.width = 56
>>> image.size
(56, 28)
>>> image.height
28
>>> image.height = 68
>>> image.size
(136, 68)
>>> image.width
136
>>> # Even though the terminal can't contain the resulting height, the size is still set
>>> image.width = 200
>>> image.size
(200, 100)
>>> image.width = Size.FIT
>>> image.size
(136, 69)
>>> image.height = Size.FIT_TO_WIDTH
>>> image.size
(255, 128)
>>> image.height = Size.ORIGINAL
>>> image.size
(288, 144)
The size
property can only be set to a
Size
enum member, resulting in dynamic size.
>>> image = from_file("python.png")
>>> image.size = Size.FIT
>>> image.size is image.width is image.height is Size.FIT
True
>>> image.size = Size.FIT_TO_WIDTH
>>> image.size is image.width is image.height is Size.FIT_TO_WIDTH
True
>>> image.size = Size.ORIGINAL
>>> image.size is image.width is image.height is Size.ORIGINAL
True
Important
The currently set cell ratio is also taken into consideration when calculating sizes for images of Text-based Render Styles.
There is a 2-line difference between the default frame size and the terminal size to allow for shell prompts and the likes.
Tip
See set_size()
for extended sizing control.
To explore more of the library’s features and functionality, check out the User Guide and the API Reference.
User Guide#
Concepts#
Render Styles#
See render style.
All render style classes are designed to share a common interface (with some having extensions), making the usage of one class directly compatible with another, except when using style-specific features.
Hence, the factory functions AutoImage
,
from_file
and from_url
provide a means of render-style-agnostic usage of the library.
These functions automatically detect the best render style supported by the active terminal.
There are two main categories of render styles:
Text-based Render Styles#
Represent images using ASCII or Unicode symbols, and in some cases, with escape sequences to reproduce color.
Render style classes in this category are subclasses of
TextImage
. These include:
Graphics-based Render Styles#
Represent images with actual pixels, using terminal graphics protocols.
Render style classes in this category are subclasses of
GraphicsImage
. These include:
Render Methods#
A render style may implement multiple render methods. See the Render Methods section in the description of a render style class (that implements multiple render methods), for the description of its render methods.
Auto Cell Ratio#
Note
This concerns Text-based Render Styles only.
The is a feature which when supported, can be used to determine the cell ratio directly from the terminal emulator itself. With this feature, it is possible to always produce images of text-based render styles with correct aspect ratio.
When using either mode of AutoCellRatio
, it’s important to
note that some terminal emulators (most non-graphics-capable ones) might have queried.
See Terminal Queries.
If the program will never expect any useful input, particularly while an image’s
size is being set/calculated, then using DYNAMIC
mode is OK. For an image with dynamic size, this includes when it’s being
rendered and when its rendered_size
,
rendered_width
or
rendered_height
property is invoked.
Otherwise i.e if the program will be expecting input, use
FIXED
mode and use
read_tty_all()
to read all currently unread input just
before calling set_cell_ratio()
.
The Active Terminal#
See active terminal.
The following streams/files are checked in the following order (along with the rationale behind the ordering):
STDOUT
: Since it’s where images will most likely be drawn.STDIN
: If output is redirected to a file or pipe and the input is a terminal, then using it as the active terminal should give the expected result i.e the same as when output is not redirected.STDERR
: If both output and input are redirected, it’s usually unlikely for errors to be./dev/tty
: Finally, if all else fail, fall back to the process’ controlling terminal, if any.
The first one that is ascertained to be a terminal device is used for all Terminal Queries and to retrieve the terminal (and window) size on some terminal emulators.
Note
If none of the streams/files is a TTY device, then a
TermImageWarning
is issued and dependent functionality is disabled.
Terminal Queries#
Some features of this library require the acquisition of certain information from the active terminal. A single iteration of this acquisition procedure is called a query.
A query involves three major steps:
Clear all unread input from the terminal
Write to the terminal
Read from the terminal
For this procedure to be successful, it must not be interrupted.
- About #1
If the program is expecting input, use
read_tty_all()
to read all currently unread input (without blocking) just before any operation involving a query.- About #2 and #3
After sending a request to the terminal, its response is awaited. The default wait time is
DEFAULT_QUERY_TIMEOUT
but can be changed usingset_query_timeout()
. If the terminal emulator responds after the set timeout, this can result in the application program receiving what would seem to be garbage or ghost input (see this FAQ).If the program includes any other function that could write to the terminal OR especially, read from the terminal or modify it’s attributes, while a query is in progress (as a result of asynchronous execution e.g multithreading or multiprocessing), decorate it with
lock_tty()
to ensure it doesn’t interfere.For example, an image viewer based on this project uses urwid which reads from the terminal using
urwid.raw_display.Screen.get_available_raw_input()
. To prevent this method from interfering with terminal queries, it usesUrwidImageScreen
which overrides and wraps the method like:class UrwidImageScreen(Screen): @lock_tty def get_available_raw_input(self): return super().get_available_raw_input()
Also, if the active terminal is not the controlling terminal of the process using this library (e.g output is redirected to another TTY device), ensure no process that can interfere with a query (e.g a shell or REPL) is currently running in the active terminal. For instance, such a process can be temporarily put to sleep.
Features that require terminal queries#
In parentheses are the outcomes when the terminal doesn’t support queries or when queries are disabled.
Auto Cell Ratio (determined to be unsupported)
Support checks for Graphics-based Render Styles (determined to be unsupported)
Auto background color (black is used)
Alpha blend for pixels above the alpha threshold in transparent renders with Text-based Render Styles (black is used)
Workaround for ANSI background colors in text-based renders on the Kitty terminal (the workaround is disabled)
Note
This list might not always be complete. In case you notice
any difference with any unlisted feature when terminal queries are enabled versus when disabled, or
a behaviour different from the one specified for the listed features, when terminal queries are disabled,
please open an issue here.
Render Formatting#
Render formatting is simply the modification of a primary render output. This is provided via:
Python’s string formatting protocol by using
format()
,str.format()
or formatted string literals with the Render Format SpecificationParameters of
draw()
The following constitute render formatting:
Padding#
This adds whitespace around a primary render output. The amount of whitespace added is determined by two values (with respect to the rendered size):
padding width, determines horizontal padding
uses the
width
field of the Render Format Specificationuses the pad_width parameter of
draw()
padding height, determines vertical padding
uses the
height
field of the Render Format Specificationuses the pad_height parameter of
draw()
If the padding width or height is less than or equal to the width or height of the primary render output, then the padding has no effect on the corresponding axis.
Alignment#
This determines the position of a primary render output within it’s Padding. The position is determined by two values:
horizontal alignment, determines the horizontal position
uses the
h_align
field of the Render Format Specificationuses the h_align parameter of
draw()
vertical alignment, determines the vertical position
uses the
v_align
field of the Render Format Specificationuses the v_align parameter of
draw()
Transparency#
This determines how transparent pixels are rendered. Transparent pixels can be rendered in one of the following ways:
Transparency disabled
Alpha channel is ignored.
uses the
#
field of the Render Format Specification, withoutthreshold
orbgcolor
uses the alpha parameter of
draw()
, set toNone
Transparency enabled with an alpha threshold
For Text-based Render Styles, any pixel with an alpha value above the given threshold is taken as opaque. For Graphics-based Render Styles, the alpha value of each pixel is used as-is.
uses the
threshold
field of the Render Format Specification
Transparent pixels overlaid on a color
May be specified to be a specific color or the default background color of the terminal emulator (if it can’t be determined, black is used).
uses the
bgcolor
field of the Render Format Specificationuses the alpha parameter of
draw()
, set to a string value
Render Format Specification#
[ <h_align> ] [ <width> ] [ . [ <v_align> ] [ <height> ] ] [ # [ <threshold> | <bgcolor> ] ] [ + <style> ]
Note
spaces are only for clarity and not included in the syntax
<...>
is a placeholder for a single field|
implies mutual exclusivityfields within
[ ]
are optionalfields within
{ }
are required, though subject to any enclosing[ ]
if the
.
is present, then at least one ofv_align
andheight
must be present
h_align
→ horizontal alignment<
→ left|
→ center>
→ rightdefault → center
width
→ padding widthpositive integer
default: terminal width
if less than or equal to the rendered width, it has no effect
v_align
→ vertical alignment^
→ top-
→ middle_
→ bottomdefault → middle
height
→ padding heightpositive integer
default: terminal height minus two (
2
)if less than or equal to the rendered height, it has no effect
#
→ transparency settingdefault: transparency is enabled with the default alpha threshold
threshold
→ alpha thresholda float value in the range
0.0
<=threshold
<1.0
(but starting with the.
(decimal point))applies to only Text-based Render Styles
e.g
.0
,.325043
,.999
bgcolor
→ background underlay color#
→ the terminal emulator’s default background color (or black, if undetermined), ORa hex color e.g
ffffff
,7faa52
if neither
threshold
norbgcolor
is present, but#
is present, transparency is disabled i.e alpha channel is ignored
style
→ style-specific format specifierSee each render style in Image Classes for its own specification, if it defines.
style
can be broken down into[ <parent> ] [ <current> ]
, wherecurrent
is the spec defined by a render style andparent
is the spec defined by a parent of that render style.parent
can in turn be recursively broken down as such.
See also
Formatted rendering tutorial.
API Reference#
Attention
đźš§ Under Construction - There might be incompatible interface changes between minor versions of version zero!
If you want to use the library in a project while it’s still on version zero,
ensure you pin the dependency to a specific minor version e.g >=0.4,<0.5
.
On this note, you probably also want to switch to the specific documentation for the version you’re using (somewhere at the lower left corner of this page).
Attention
Any module or definition not documented here should be considered part of the private interface and can be changed or removed at any time without notice.
Top-Level Definitions#
Constants#
- term_image.DEFAULT_QUERY_TIMEOUT: float = 0.1#
Default timeout for Terminal Queries
See also:
set_query_timeout()
Enumerations#
- class term_image.AutoCellRatio(value)[source]#
Bases:
enum.Enum
Values for setting Auto Cell Ratio.
- is_supported: bool | None = None#
Auto cell ratio support status. Can be
None
-> support status not yet determinedTrue
-> supportedFalse
-> not supported
Can be explicitly set when using auto cell ratio but want to avoid the support check in a situation where the support status is foreknown. Can help to avoid being wrongly detected as unsupported on a queried terminal that doesn’t respond on time.
For instance, when using multiprocessing, if the support status has been determined in the main process, this value can simply be passed on to and set within the child processes.
- FIXED#
- DYNAMIC#
See
set_cell_ratio()
.
Functions#
Disables Terminal Queries. |
|
Disables a workaround for terminal emulators that wrongly report window dimensions swapped. |
|
Re-Enables Terminal Queries. |
|
Enables a workaround for terminal emulators that wrongly report window dimensions swapped. |
|
Returns the global cell ratio. |
|
Sets the global cell ratio. |
|
Sets the timeout for Terminal Queries. |
- term_image.disable_queries()[source]#
Disables Terminal Queries.
To re-enable queries, call
enable_queries()
.Note
This affects all dependent features.
- term_image.disable_win_size_swap()[source]#
Disables a workaround for terminal emulators that wrongly report window dimensions swapped.
This workaround is disabled by default. While disabled, the window dimensions reported by the active terminal are used as-is.
Note
This affects Auto Cell Ratio computation and size computations for Graphics-based Render Styles.
- term_image.enable_queries()[source]#
Re-Enables Terminal Queries.
Queries are enabled by default. To disable, call
disable_queries()
.Note
This affects all dependent features.
- term_image.enable_win_size_swap()[source]#
Enables a workaround for terminal emulators that wrongly report window dimensions swapped.
While enabled, the window dimensions reported by the active terminal are swapped. This workaround is required on some older VTE-based terminal emulators.
Note
This affects Auto Cell Ratio computation and size computations for Graphics-based Render Styles.
- term_image.get_cell_ratio()[source]#
Returns the global cell ratio.
See
set_cell_ratio()
.
- term_image.set_cell_ratio(ratio)[source]#
Sets the global cell ratio.
- Parameters:
ratio (float | term_image.AutoCellRatio) –
Can be one of the following values.
A positive
float
value.AutoCellRatio.FIXED
, the ratio is immediately determined from the active terminal.AutoCellRatio.DYNAMIC
, the ratio is determined from the active terminal wheneverget_cell_ratio()
is called, though with some caching involved, such that the ratio is re-determined only if the terminal size changes.
- Raises:
TypeError – An argument is of an inappropriate type.
ValueError – An argument is of an appropriate type but has an unexpected/invalid value.
term_image.exceptions.TermImageError – Auto cell ratio is not supported in the active terminal or on the current platform.
This value is taken into consideration when setting image sizes for text-based render styles, in order to preserve the aspect ratio of images drawn to the terminal.
Note
Changing the cell ratio does not automatically affect any image that has a fixed size. For a change in cell ratio to take effect, the image’s size has to be re-set.
Attention
See Auto Cell Ratio for details about the auto modes.
- term_image.set_query_timeout(timeout)[source]#
Sets the timeout for Terminal Queries.
- Parameters:
timeout (float) – Time limit for awaiting a response from the terminal, in seconds.
- Raises:
TypeError – timeout is not a float.
ValueError – timeout is less than or equal to zero.
image
Module#
Functions#
These functions automatically detect the best supported render style for the current terminal.
Since all classes share a common interface (as defined by BaseImage
),
any operation supported by one image class can be performed on any other image class,
except style-specific operations.
Selects the image render style that best suits the current terminal emulator. |
|
Creates an image instance from a PIL image instance. |
|
Creates an image instance from an image file. |
|
Creates an image instance from an image URL. |
- term_image.image.auto_image_class()[source]#
Selects the image render style that best suits the current terminal emulator.
- Returns:
An image class (a subclass of
BaseImage
).- Return type:
term_image.image.common.ImageMeta
- term_image.image.AutoImage(image, *, width=None, height=None)[source]#
Creates an image instance from a PIL image instance.
- Returns:
An instance of the automatically selected image render style (as returned by
auto_image_class()
).- Return type:
Same arguments and raised exceptions as the
BaseImage
class constructor.
- term_image.image.from_file(filepath, **kwargs)[source]#
Creates an image instance from an image file.
- Returns:
An instance of the automatically selected image render style (as returned by
auto_image_class()
).- Return type:
Same arguments and raised exceptions as
BaseImage.from_file()
.
- term_image.image.from_url(url, **kwargs)[source]#
Creates an image instance from an image URL.
- Returns:
An instance of the automatically selected image render style (as returned by
auto_image_class()
).- Return type:
Same arguments and raised exceptions as
BaseImage.from_url()
.
Enumerations#
Image source type. |
|
Enumeration for automatic sizing. |
- class term_image.image.ImageSource(value)[source]#
Bases:
enum.Enum
Image source type.
- FILE_PATH#
The instance was derived from a path to a local image file.
- PIL_IMAGE#
The instance was derived from a PIL image instance.
- URL#
The instance was derived from an image URL.
- class term_image.image.Size(value)[source]#
Bases:
enum.Enum
Enumeration for automatic sizing.
- AUTO#
Equivalent to
ORIGINAL
if it will fit into the frame size, elseFIT
.
- FIT#
The image size is set to fit optimally within the frame size.
- FIT_TO_WIDTH#
The size is set such that the width is exactly the frame width, regardless of the cell ratio.
- ORIGINAL#
The image size is set such that the image is rendered with as many pixels as the the original image consists of.
Image Classes#
Class Hierarchy#
The Classes#
Base of all render styles. |
|
Base of all Text-based Render Styles. |
|
A render style using unicode half blocks and 24-bit colour escape codes. |
|
Base of all Graphics-based Render Styles. |
|
A render style using the iTerm2 inline image protocol. |
|
A render style using the Kitty terminal graphics protocol. |
- class term_image.image.BaseImage(image, *, width=None, height=None)[source]#
Bases:
object
Base of all render styles.
- Parameters:
- Raises:
TypeError – An argument is of an inappropriate type.
ValueError – An argument is of an appropriate type but has an unexpected/invalid value.
Propagates exceptions raised by
set_size()
, if width or height is given.Note
If neither width nor height is given (or both are
None
),FIT
applies.If both width and height are not
None
, they must be positive integers and manual sizing applies i.e the image size is set as given without preserving aspect ratio.For animated images, the seek position is initialized to the current seek position of the given image.
It’s allowed to set properties for animated images on non-animated ones, the values are simply ignored.
Attention
This class cannot be directly instantiated. Image instances should be created from its subclasses.
Instance Properties:
Instance finalization status
Duration of a single frame
Image height
Animatability of the image
Size of the source (in pixels)
Image frame count
The height with which the image is rendered
The size with which the image is rendered
The width with which the image is rendered
Image size
Image source
Image source type
Image width
Class Properties:
Forced render style support
Instance Methods:
Finalizes the instance and releases external resources.
Draws the image to standard output.
Changes current image frame.
Sets the image size (with extended control).
Returns the current image frame number.
Class Methods:
Creates an instance from an image file.
Creates an instance from an image URL.
Checks if the implemented render style is supported by the active terminal.
Class/Instance Methods:
Sets the render method used by instances of a render style class that implements multiple render methods.
- property closed#
Instance finalization status
- Type:
- GET:
Returns
True
if the instance has been finalized (close()
has been called). Otherwise,False
.
- property forced_support#
Forced render style support
- Type:
- GET:
Returns the forced support status of the invoking class or class of the invoking instance.
- SET:
Forced support is enabled or disabled for the invoking class.
Can not be set on an instance.
If forced support is:
enabled, the render style is treated as if it were supported, regardless of the return value of
is_supported()
.disabled, the return value of
is_supported()
determines if the render style is supported or not.
By default, forced support is disabled for all render style classes.
Note
This property is descendant.
This doesn’t affect the return value of
is_supported()
but may affect operations that require that a render style be supported e.g instantiation of some render style classes.
- property frame_duration#
Duration of a single frame
- Type:
Optional[float]
- GET:
Returns:
The duration of a single frame (in seconds), if the image is animated.
None
, if otherwise.
- SET:
If the image is animated, The frame duration is set. Otherwise, nothing is done.
- property height#
Image height
- GET:
Returns:
- SET:
If set to:
a positive
int
; the image height is set to the given value and the width is set proportionally.a
Size
enum member; the image size is set as prescibed by the enum member.None
; equivalent toFIT
.
This results in a fixed size.
- property is_animated#
Animatability of the image
- Type:
- GET:
Returns
True
if the image is animated. Otherwise,False
.
- property original_size#
Size of the source (in pixels)
- GET:
Returns the source size.
- property rendered_height#
The height with which the image is rendered
- Type:
- GET:
Returns the number of lines the image will occupy when drawn in a terminal.
- property rendered_size#
The size with which the image is rendered
- GET:
Returns the number of columns and lines (respectively) the image will occupy when drawn in a terminal.
- property rendered_width#
The width with which the image is rendered
- Type:
- GET:
Returns the number of columns the image will occupy when drawn in a terminal.
- property size#
Image size
- GET:
Returns:
- SET:
If set to a:
Size
enum member, the image size is set as prescibed by the given member.This results in a dynamic size i.e the size is computed whenever the image is rendered using the default frame size.
2-tuple of integers,
(width, height)
, the image size set as given.This results in a fixed size i.e the size will not change until it is re-set.
- property source#
Image source
- Type:
Union[PIL.Image.Image, str]
- GET:
Returns the source from which the instance was initialized.
- property source_type#
Image source type
- Type:
- GET:
Returns the type of source from which the instance was initialized.
- property width#
Image width
- GET:
Returns:
- SET:
If set to:
a positive
int
; the image width is set to the given value and the height is set proportionally.a
Size
enum member; the image size is set as prescibed by the enum member.None
; equivalent toFIT
.
This results in a fixed size.
- close()[source]#
Finalizes the instance and releases external resources.
In most cases, it’s not necessary to explicitly call this method, as it’s automatically called when the instance is garbage-collected.
This method can be safely called multiple times.
If the instance was initialized with a PIL image, the PIL image is never finalized.
- draw(h_align=None, pad_width=0, v_align=None, pad_height=-2, alpha=0.1568627450980392, *, animate=True, repeat=-1, cached=100, scroll=False, check_size=True, **style)[source]#
Draws the image to standard output.
- Parameters:
h_align (Optional[str]) – Horizontal alignment (“left” / “<”, “center” / “|” or “right” / “>”). Default: center.
pad_width (int) –
Number of columns within which to align the image.
Excess columns are filled with spaces.
Must not be greater than the terminal width.
v_align (Optional[str]) – Vertical alignment (“top”/”^”, “middle”/”-” or “bottom”/”_”). Default: middle.
pad_height (int) –
Number of lines within which to align the image.
Excess lines are filled with spaces.
Must not be greater than the terminal height, for animations.
alpha (Optional[float, str]) –
Transparency setting.
If
None
, transparency is disabled (alpha channel is removed).If a
float
(0.0 <= x < 1.0), specifies the alpha ratio above which pixels are taken as opaque. (Applies to only text-based render styles).If a string, specifies a color to replace transparent background with. Can be:
”#” -> The terminal’s default background color (or black, if undetermined) is used.
A hex color e.g
ffffff
,7faa52
.
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.
Determines if rendered frames of an animated image will be cached (for speed up of subsequent renders of the same frame) or not.
scroll (bool) – Only applies to non-animations. If
True
, allows the image’s rendered height to be greater than the terminal height.check_size (bool) – If
False
, rendered size validation is not performed for non-animations. Does not affect padding size validation.style (Any) – Style-specific render parameters. See each subclass for it’s own usage.
- Raises:
TypeError – An argument is of an inappropriate type.
ValueError – An argument is of an appropriate type but has an unexpected/invalid value.
term_image.exceptions.InvalidSizeError – The image’s rendered size can not fit into the terminal size.
term_image.exceptions.StyleError – Unrecognized style-specific render parameter(s).
term_image.exceptions.RenderError – An error occurred during rendering.
If pad_width or pad_height is:
positive, it is absolute and used as-is.
non-positive, it is relative to the corresponding terminal dimension (at the point of calling this method) and equivalent to the absolute dimension
max(terminal_dimension + frame_dimension, 1)
.
padding width is always validated.
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 is always validated, if set.
Padding height is always validated.
Animations, by default, are infinitely looped and can be terminated with
SIGINT
(CTRL + C
), without raisingKeyboardInterrupt
.
- classmethod from_file(filepath, **kwargs)[source]#
Creates an instance from an image file.
- Parameters:
filepath (str | os.PathLike) – Relative/Absolute path to an image file.
kwargs (None | int) – Same keyword arguments as the class constructor.
- Returns:
A new instance.
- Raises:
TypeError – filepath is of an inappropriate type.
FileNotFoundError – The given path does not exist.
IsADirectoryError – Propagated from from
PIL.Image.open()
.PIL.UnidentifiedImageError – Propagated from from
PIL.Image.open()
.
- Return type:
Also Propagates exceptions raised or propagated by the class constructor.
- classmethod from_url(url, **kwargs)[source]#
Creates an instance from an image URL.
- Parameters:
- Returns:
A new instance.
- Raises:
TypeError – url 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:
Also propagates connection-related exceptions from
requests.get()
and exceptions raised or propagated by the class constructor.Note
This method creates a temporary file, but only after successful initialization. The file is removed:
when
close()
is called,upon exiting a
with
statement block that uses the instance as a context manager, orwhen the instance is garbage collected.
- abstract classmethod is_supported()[source]#
Checks if the implemented render style is supported by the active terminal.
- Returns:
True
if the render style implemented by the invoking class is supported by the active terminal. Otherwise,False
.- Return type:
Attention
Support checks for most (if not all) render styles require querying the active terminal the first time they’re executed.
Hence, it’s advisable to perform all necessary support checks (call this method on required style classes) at an early stage of a program, before user input is expected. If using automatic style selection, calling
auto_image_class()
only should be sufficient.
- seek(pos)[source]#
Changes current image frame.
- Parameters:
pos (int) – New frame number.
- Raises:
TypeError – An argument is of an inappropriate type.
ValueError – An argument is of an appropriate type but has an unexpected/invalid value.
Frame numbers start from 0 (zero).
- classmethod set_render_method(method=None)[source]#
Sets the render method used by instances of a render style class that implements multiple render methods.
- Parameters:
method (str | None) – The render method to be set or
None
for a reset (case-insensitive).- Raises:
TypeError – An argument is of an inappropriate type.
ValueError – An argument is of an appropriate type but has an unexpected/invalid value.
See the Render Methods section in the description of subclasses that implement such for their specific usage.
If method is not
None
and this method is called via:a class, the class-wide render method is set.
an instance, the instance-specific render method is set.
If method is
None
and this method is called via:a class, the class-wide render method is unset, so that it uses that of its parent style class (if any) or the default.
an instance, the instance-specific render method is unset, so that it uses the class-wide render method thenceforth.
Any instance without a render method set uses the class-wide render method.
Note
method =
None
is always allowed, even if the render style doesn’t implement multiple render methods.The class-wide render method is descendant.
- set_size(width=None, height=None, frame_size=(0, -2))[source]#
Sets the image size (with extended control).
- Parameters:
width (int | term_image.image.common.Size | None) –
Can be
a positive integer; horizontal dimension of the image, in columns.
a
Size
enum member.
height (int | term_image.image.common.Size | None) –
Can be
a positive integer; vertical dimension of the image, in lines.
a
Size
enum member.
frame_size (Tuple[int, int]) –
Frame size,
(columns, lines)
. If columns or lines ispositive, it is absolute and used as-is.
non-positive, it is relative to the corresponding terminal dimension and equivalent to the absolute dimension
max(terminal_dimension + frame_dimension, 1)
.
This is used only when neither width nor height is an
int
.
- Raises:
TypeError – An argument is of an inappropriate type.
ValueError – An argument is of an appropriate type but has an unexpected/invalid value.
If both width and height are not
None
, they must be positive integers and manual sizing applies i.e the image size is set as given without preserving aspect ratio.If width or height is a
Size
enum member, automatic sizing applies as prescribed by the enum member.If neither width nor height is given (or both are
None
),FIT
applies.
- class term_image.image.TextImage(image, *, width=None, height=None)[source]#
Bases:
term_image.image.common.BaseImage
Base of all Text-based Render Styles.
See
BaseImage
for the description of the constructor.Important
Instantiation of subclasses is always allowed, even if the current terminal does not [fully] support the render style.
To check if the render style is fully supported in the current terminal, use
is_supported()
.Attention
This class cannot be directly instantiated. Image instances should be created from its subclasses.
- class term_image.image.BlockImage(image, *, width=None, height=None)[source]#
Bases:
term_image.image.common.TextImage
A render style using unicode half blocks and 24-bit colour escape codes.
See
TextImage
for the description of the constructor.
- class term_image.image.GraphicsImage(image, *, width=None, height=None)[source]#
Bases:
term_image.image.common.BaseImage
Base of all Graphics-based Render Styles.
- Raises:
term_image.exceptions.StyleError – The active terminal doesn’t support the render style.
See
BaseImage
for the description of the constructor.Attention
This class cannot be directly instantiated. Image instances should be created from its subclasses.
Tip
To allow instantiation regardless of whether the render style is supported or not, enable
forced_support
.
- class term_image.image.ITerm2Image(image, *, width=None, height=None)[source]#
Bases:
term_image.image.common.GraphicsImage
A render style using the iTerm2 inline image protocol.
See
GraphicsImage
for the complete description of the constructor.Render Methods
ITerm2Image
provides two methods of rendering images, namely:- LINES (default)
Renders an image line-by-line i.e the image is evenly split across the number of lines it should occupy.
Pros:
Good for use cases where it might be required to trim some lines of the image.
Cons:
Image drawing is significantly slower on iTerm2 due to the terminal emulator’s performance.
- WHOLE
Renders an image all at once i.e the entire image data is encoded into one line of the render output, such that the entire image is drawn once by the terminal and still occupies the correct amount of lines and columns.
Pros:
Render results are more compact (i.e less in character count) than with the LINES method since the entire image is encoded at once.
Image drawing is faster than with LINES on most terminals.
Smoother animations.
Cons:
This method currently doesn’t work well on iTerm2 and WezTerm when the image height is greater than the terminal height.
- ANIM
Renders an animated image to utilize the protocol’s native animation feature [1].
Similar to the WHOLE render method, except that the terminal emulator animates the image, provided it supports the feature of the protocol. The animation is completely controlled by the terminal emulator.
Note
If the image data size (in bytes) is greater than the value of
native_anim_max_bytes
, a warning is issued.If used with
ImageIterator
or an animation, the WHOLE render method is used instead.If the image is non-animated, the WHOLE render method is used instead.
Note
The LINES method is the default only because it works properly in all cases, it’s more advisable to use the WHOLE method except when the image height is greater than the terminal height or when trimming the image is required.
The render method can be set with
set_render_method()
using the names specified above.Style-Specific Render Parameters
See
BaseImage.draw()
(particularly the style parameter).method (None | str) → Render method override.
None
→ the current effective render method of the instance is used.default →
None
mix (bool) → Cell content inter-mix policy (Only supported on WezTerm, ignored otherwise).
False
→ existing contents of cells within the region covered by the drawn render output are erasedTrue
→ existing cell contents show under transparent areas of the drawn render outputdefault →
False
compress (int) → ZLIB compression level, for renders re-encoded in PNG format.
0
<= compress <=9
1
→ best speed,9
→ best compression,0
→ no compressiondefault →
4
Results in a trade-off between render time and data size/draw speed
Format Specification
See Render Format Specification.
[ <method> ] [ m <mix> ] [ c <compress> ]
method
→ render method overrideL
→ LINES render method (current frame only, for animated images)W
→ WHOLE render method (current frame only, for animated images)A
→ ANIM render method [1]default → current effective render method of the instance
m
→ cell content inter-mix policy (Only supported in WezTerm, ignored otherwise)mix
→ inter-mix policy0
→ existing contents of cells in the region covered by the drawn render output will be erased1
→ existing cell contents show under transparent areas of the drawn render output
default →
m0
e.g
m0
,m1
c
→ ZLIB compression level, for renders re-encoded in PNG formatcompress
→ compression levelAn integer in the range
0
<=x
<=9
1
→ best speed,9
→ best compression,0
→ no compression
default →
c4
e.g
c0
,c9
Results in a trade-off between render time and data size/draw speed
Class/Instance Properties:
JPEG encoding quality
Read-from-file optimization
Class Properties:
Maximum size (in bytes) of image data for native animation
Class Methods:
Clears images.
- property jpeg_quality#
JPEG encoding quality
- Type:
- GET:
Returns the effective JPEG encoding quality of the invoker (class or instance).
- SET:
If invoked via:
a class, the class-wide quality is set.
an instance, the instance-specific quality is set.
- DELETE:
If invoked via:
a class, the class-wide quality is unset.
an instance, the instance-specific quality is unset.
If:
value <
0
; JPEG encoding is disabled.0
<= value <=95
; JPEG encoding is enabled with the given quality.
If unset for:
a class, it uses that of its parent iterm2 style class (if any) or the default (disabled), if unset for all parents or the class has no parent iterm2 style class.
an instance, it uses that of its class.
By default, the quality is unset (i.e JPEG encoding is disabled) and images are encoded in the PNG format (when not reading directly from file) but in some cases, higher and/or faster compression may be desired. JPEG encoding is significantly faster than PNG encoding and produces smaller (in data size) output but at the cost of image quality.
Note
This property is descendant.
This optimization applies to only re-encoded (i.e not read directly from file) non-transparent renders.
Tip
The transparency status of some images can not be correctly determined in an efficient way at render time. To ensure JPEG encoding is always used for a re-encoded render, disable transparency or set a background color.
Furthermore, to ensure that renders with the WHOLE render method are always re-encoded, disable
read_from_file
.This optimization is useful in improving non-native animation performance.
See also
the alpha parameter of
draw()
and the#
,bgcolor
fields of the Render Format Specification
- property native_anim_max_bytes#
Maximum size (in bytes) of image data for native animation
- Type:
- GET:
Returns the set value.
- SET:
A positive integer; the value is set.
Can not be set via an instance.
- DELETE:
The value is reset to the default.
Can not be reset via an instance.
TermImageWarning
is issued (and shown only the first time, except the warning filters are modified to do otherwise) if the image data size for a native animation is above this value.Note
This property is a global setting. Hence, setting/resetting it on this class or any subclass affects all classes and their instances.
Warning
This property should be altered with caution to avoid excessive memory usage, particularly on the terminal emulator’s end.
- property read_from_file#
Read-from-file optimization
- Type:
- GET:
Returns the effective read-from-file policy of the invoker (class or instance).
- SET:
If invoked via:
a class, the class-wide policy is set.
an instance, the instance-specific policy is set.
- DELETE:
If invoked via:
a class, the class-wide policy is unset.
an instance, the instance-specific policy is unset.
If the value is:
True
, image data is read directly from file when possible and no image manipulation is required.False
, images are always re-encoded (in the PNG format by default).
If unset for:
a class, it uses that of its parent iterm2 style class (if any) or the default (
True
), if unset for all parents or the class has no parent iterm2 style class.an instance, it uses that of its class.
By default, the policy is unset, which is equivalent to
True
i.e the optimization is enabled.Note
This property is descendant.
This is an optimization to reduce render times and is only applicable to the WHOLE render method, since the the LINES method inherently requires image manipulation.
This property does not affect animations. Native animations are always read from file when possible and frames of non-native animations have to be re-encoded.
See also
- classmethod clear(cursor=False, now=False)[source]#
Clears images.
- Parameters:
cursor (bool) – If
True
, all images intersecting with the current cursor position are cleared. Otherwise, all visible images are cleared.now (bool) – If
True
the images are cleared immediately, without affecting any standard I/O stream. Otherwise they’re cleared when nextsys.stdout
is flushed.
Note
Required and works only on Konsole, as text doesn’t overwrite images.
- class term_image.image.KittyImage(image, *, width=None, height=None)[source]#
Bases:
term_image.image.common.GraphicsImage
A render style using the Kitty terminal graphics protocol.
See
GraphicsImage
for the complete description of the constructor.Render Methods
KittyImage
provides two methods of rendering images, namely:- LINES (default)
Renders an image line-by-line i.e the image is evenly split across the number of lines it should occupy.
Pros:
Good for use cases where it might be required to trim some lines of the image.
- WHOLE
Renders an image all at once i.e the entire image data is encoded into one line of the rendered output, such that the entire image is drawn once by the terminal and still occupies the correct amount of lines and columns.
Pros:
Render results are more compact (i.e less in character count) than with the LINES method since the entire image is encoded at once.
The render method can be set with
set_render_method()
using the names specified above.Style-Specific Render Parameters
See
BaseImage.draw()
(particularly the style parameter).method (None | str) → Render method override.
None
→ the current effective render method of the instance is used.default →
None
z_index (int) → The stacking order of graphics and text for non-animations.
An integer in the signed 32-bit range (excluding
-(2**31)
)>= 0
→ the image will be drawn above text< 0
→ the image will be drawn below text< -(2**31)/2
→ the image will be drawn below cells with non-default background colordefault →
0
Overlapping graphics on different z-indexes will be blended (by the terminal emulator) if they are semi-transparent.
To inter-mix text with graphics, see the mix parameter.
mix (bool) → Graphics/Text inter-mix policy.
False
→ text within the region covered by the drawn render output will be erased, though text can be inter-mixed with graphics after drawingTrue
→ text within the region covered by the drawn render output will NOT be eraseddefault →
False
compress (int) → ZLIB compression level.
0
<= compress <=9
1
→ best speed,9
→ best compression,0
→ no compressiondefault →
4
Results in a trade-off between render time and data size/draw speed
Format Specification
See Render Format Specification.
[ <method> ] [ z <z-index> ] [ m <mix> ] [ c <compress> ]
method
→ render method overrideL
→ LINES render method (current frame only, for animated images)W
→ WHOLE render method (current frame only, for animated images)default → Current effective render method of the image
z
→ graphics/text stacking orderz-index
→ z-indexAn integer in the signed 32-bit range (excluding
-(2**31)
)>= 0
→ the render output will be drawn above text< 0
→ the render output will be drawn below text< -(2**31)/2
→ the render output will be drawn below cells with non-default background color
default →
z0
(z-index zero)e.g
z0
,z1
,z-1
,z2147483647
,z-2147483648
overlapping graphics on different z-indexes will be blended (by the terminal emulator) if they are semi-transparent
m
→ graphics/text inter-mix policymix
→ inter-mix policy0
→ text within the region covered by the drawn render output will be erased, though text can be inter-mixed with graphics after drawing1
→ text within the region covered by the drawn render output will NOT be erased
default →
m0
e.g
m0
,m1
c
→ ZLIB compression levelcompress
→ compression levelAn integer in the range
0
<=compress
<=9
1
→ best speed,9
→ best compression,0
→ no compression
default →
c4
e.g
c0
,c9
results in a trade-off between render time and data size/draw speed
Class Methods:
Clears images.
- classmethod clear(*, cursor=False, z_index=None, now=False)[source]#
Clears images.
- Parameters:
cursor (bool) – If
True
, all images intersecting with the current cursor position are cleared.z_index (int | None) – An integer in the signed 32-bit range. If given, all images on the given z-index are cleared.
now (bool) – If
True
the images are cleared immediately, without affecting any standard I/O stream. Otherwise they’re cleared when nextsys.stdout
is flushed.
Aside now, only one other argument may be given. If no argument is given (aside now) or default values are given, all images visible on the screen are cleared.
Note
This method does nothing if the render style is not supported.
Context Management Protocol Support#
BaseImage
instances are context managers i.e they can be used with the with
statement as in:
with from_url(url) as image:
...
Using an instance as a context manager guarantees instant object finalization
(i.e clean-up/release of resources), especially for instances with URL sources
(see BaseImage.from_url()
).
Iteration Support#
Animated images 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 from_file("animated.gif"):
...
Subsequent frames of the image are yielded on subsequent iterations.
Note
iter(anim_image)
returns anImageIterator
instance with a repeat count of1
, hence caching is disabled.The frames are unformatted and transparency is enabled i.e as returned by
str(image)
.
For extensive or custom iteration, use ImageIterator
directly.
Other Classes#
- class term_image.image.ImageIterator(image, repeat=-1, format_spec='', cached=100)[source]#
Bases:
object
Efficiently iterate over rendered frames of an animated image
- Parameters:
image (BaseImage) – Animated image.
repeat (int) – The number of times to go over the entire image. A negative value implies infinite repetition.
format_spec (str) – The format specifier for the rendered frames (default: auto).
Determines if the rendered frames will be cached (for speed up of subsequent renders) or not. If it is
a boolean, caching is enabled if
True
. Otherwise, caching is disabled.a positive integer, caching is enabled only if the framecount of the image is less than or equal to the given number.
- Raises:
TypeError – An argument is of an inappropriate type.
ValueError – An argument is of an appropriate type but has an unexpected/invalid value.
term_image.exceptions.StyleError – Invalid style-specific format specifier.
If repeat equals
1
, caching is disabled.The iterator has immediate response to changes in the image size.
If the image size is dynamic, it’s computed per frame.
The number of the last yielded frame is set as the image’s seek position.
Directly adjusting the seek position of the image doesn’t affect iteration. Use
ImageIterator.seek()
instead.After the iterator is exhausted, the underlying image is set to frame
0
.
Instance Properties:
Iteration repeat countdown
Instance Methods:
Closes the iterator and releases resources used.
Sets the frame number to be yielded on the next iteration without affecting the repeat count.
- property loop_no#
Iteration repeat countdown
- Type:
Optional[int]
- GET:
Returns:
None
, if iteration hasn’t started.Otherwise, the current iteration repeat countdown value.
Changes on the first iteration of each loop, except for infinite iteration where it’s always
-1
. When iteration has ended, the value is zero.
- close()[source]#
Closes the iterator and releases resources used.
Does not reset the frame number of the underlying image.
Note
This method is automatically called when the iterator is exhausted or garbage-collected.
- seek(pos)[source]#
Sets the frame number to be yielded on the next iteration without affecting the repeat count.
- Parameters:
pos (int) – Next frame number.
- Raises:
TypeError – An argument is of an inappropriate type.
ValueError – An argument is of an appropriate type but has an unexpected/invalid value.
term_image.exceptions.TermImageError – Iteration has not yet started or the iterator is exhausted/closed.
Frame numbers start from
0
(zero).
widget
Module#
Classes:
Image widget (box/flow) for the urwid TUI framework. |
|
Image canvas for the urwid TUI framework. |
|
A screen that supports drawing images. |
- class term_image.widget.UrwidImage(image, format_spec='', *, upscale=False)[source]#
Bases:
urwid.widget.Widget
Image widget (box/flow) for the urwid TUI framework.
- Parameters:
image (BaseImage) – The image to be rendered by the widget.
format_spec (str) – Render format specifier. Padding width and height are ignored.
upscale (bool) – If
True
, the image will be upscaled to fit maximally within the available size, if necessary, while still preserving the aspect ratio. Otherwise, the image is never upscaled.
- Raises:
TypeError – An argument is of an inappropriate type.
ValueError – An argument is of an appropriate type but has an unexpected/invalid value.
term_image.exceptions.StyleError – Invalid style-specific format specifier.
term_image.exceptions.UrwidImageError – Too many image widgets rendering images with the kitty render style.
Any ample space in the widget’s render size is filled with spaces.For animated images, the current frame (at render-time) is rendered.Tip
If image is of a graphics-based render style and the widget is being used as or within a flow widget, with overlays or in any other case where the canvas will require vertical trimming, make sure to use a render method that splits images across lines such as the LINES render method for kitty and iterm2 render styles.
Note
The z-index style-specific format spec field for
KittyImage
is ignored as this is used internally.A maximum of
2**32 - 2
instances initialized withKittyImage
instances may exist at the same time.
Important
This is defined if and only if the
urwid
package is available.Instance Properties:
The image rendered by the widget
Class Methods:
Sets the widget to be rendered in place of an image when rendering fails.
- property image#
The image rendered by the widget
- Type:
- GET:
Returns the image instance rendered by the widget.
- classmethod set_error_placeholder(widget)[source]#
Sets the widget to be rendered in place of an image when rendering fails.
- Parameters:
widget (urwid.widget.Widget | None) – The placeholder widget or
None
to remove the placeholder.- Raises:
TypeError – widget is not an urwid widget.
If set, any exception raised during rendering is suppressed and the placeholder is rendered in place of the image.
- class term_image.widget.UrwidImageCanvas(render, size, image_size)[source]#
Bases:
urwid.canvas.Canvas
Image canvas for the urwid TUI framework.
- Parameters:
Note
The canvas outputs blanks (spaces) for graphics-based images when horizontal trimming is required (e.g when a widget is laid over an image). This is temporary as horizontal trimming will be implemented in the future.
This canvas is intended to be rendered by
UrwidImage
(or a subclass of it) only. Otherwise, the output isn’t guaranteed to be as expected.Warning
The constructor of this class performs NO argument validation at all for the sake of performance. If instantiating this class directly, make sure to pass appropriate arguments or create subclass, override the constructor and perform the validation.
Important
This is defined if and only if the
urwid
package is available.
- class term_image.widget.UrwidImageScreen(*args, **kwargs)[source]#
Bases:
urwid.raw_display.Screen
A screen that supports drawing images.
It monitors images of some graphics-based render styles and clears them off the screen when necessary (e.g at startup, when scrolling, upon terminal resize and at exit).
See the baseclass for further description.
Important
This is defined if and only if the
urwid
package is available.Instance Methods:
Clears on-screen images of graphics-based styles that support/require such an operation.
See the description of the baseclass' method.
See the baseclass' method for the description.
See the baseclass' method for the description.
See the baseclass' method for the description.
- clear_images(*widgets, now=False)[source]#
Clears on-screen images of graphics-based styles that support/require such an operation.
- Parameters:
widgets (term_image.widget.urwid.UrwidImage) –
Image widgets to clear.
All on-screen images rendered by each of the widgets are cleared, provided the widget was initialized with a
term_image.image.KittyImage
instance.If none is given, all images (of styles that support/require such an operation) on-screen are cleared.
now (bool) – If
True
the images are cleared immediately. Otherwise, they’re cleared when next the output buffer is flushed, such as at the next screen redraw.
- draw_screen(maxres, canvas)[source]#
See the description of the baseclass’ method.
Synchronizes output on terminal emulators that support the feature to reduce/eliminate image flickering and screen tearing.
Important
Synchronized with
lock_tty()
.
- flush()[source]#
See the baseclass’ method for the description.
Important
Synchronized with
lock_tty()
.
- get_available_raw_input()[source]#
See the baseclass’ method for the description.
Important
Synchronized with
lock_tty()
.
- write(data)[source]#
See the baseclass’ method for the description.
Important
Synchronized with
lock_tty()
.
exceptions
Module#
Warnings:
Package-specific warning category. |
Exceptions:
Exception baseclass. |
|
Raised for invalid image sizes. |
|
Raised for errors that occur during rendering. |
|
Raised for errors pertaining to the Style API. |
|
Raised for 404 errors. |
|
Raised for errors specific to |
- exception term_image.exceptions.TermImageWarning[source]#
Bases:
UserWarning
Package-specific warning category.
- exception term_image.exceptions.TermImageError[source]#
Bases:
Exception
Exception baseclass. Raised for generic errors.
- exception term_image.exceptions.InvalidSizeError[source]#
Bases:
term_image.exceptions.TermImageError
Raised for invalid image sizes.
- exception term_image.exceptions.RenderError[source]#
Bases:
term_image.exceptions.TermImageError
Raised for errors that occur during rendering.
If the direct cause of the error is an exception, it should typically be attached as the context of this exception i.e
raise RenderError(...) from exc
.
- exception term_image.exceptions.StyleError[source]#
Bases:
term_image.exceptions.TermImageError
Raised for errors pertaining to the Style API.
- exception term_image.exceptions.URLNotFoundError[source]#
Bases:
term_image.exceptions.TermImageError
,FileNotFoundError
Raised for 404 errors.
- exception term_image.exceptions.UrwidImageError[source]#
Bases:
term_image.exceptions.TermImageError
Raised for errors specific to
UrwidImage
.
utils
Module#
Functions:
Returns the current size of a character cell in the active terminal. |
|
Returns the name and version of the active terminal, if available. |
|
Returns the current size of the active terminal. |
|
Synchronizes access to the active terminal. |
|
Reads all available input directly from the active terminal without blocking. |
|
Writes to the active terminal and waits until complete transmission. |
- term_image.utils.get_cell_size()[source]#
Returns the current size of a character cell in the active terminal.
The speed of this implementation is almost entirely dependent on the terminal; the method it supports and its response time if it has to be queried.
Note
Currently works on UNIX only, returns
None
on any other platform or when there is no active terminal.
- term_image.utils.get_terminal_name_version()[source]#
Returns the name and version of the active terminal, if available.
- term_image.utils.get_terminal_size()[source]#
Returns the current size of the active terminal.
- Returns:
The terminal size in columns and lines.
- Return type:
Note
This implementation is quite different from
shutil.get_terminal_size()
andos.get_terminal_size()
in that it:gives the correct size of the active terminal even when output is redirected, in most cases
gives different results in certain situations
is what this library works with
- term_image.utils.lock_tty(func)[source]#
Synchronizes access to the active terminal.
- Parameters:
func (function) – The function to be wrapped.
When a decorated function is called, a re-entrant lock is acquired by the current process or thread and released after the call, such that any other decorated function called within another thread or subprocess waits until the lock is fully released (i.e has been released as many times as acquired) by the current process or thread.
Note
It works across parent-/sub-processes, started directly or indirectly via
multiprocessing.Process
(or a subclass of it), and their threads, providedmultiprocessing.synchronize
is supported on the host platform. Otherwise, a warning is issued when starting a subprocess.Warning
If
multiprocessing.synchronize
is supported and a subprocess is started within a call (possibly recursive) to a decorated function, the thread in which that occurs will be out of sync until that call returns. Hence, avoid starting a subprocess within a decorated function.
- term_image.utils.read_tty_all()[source]#
Reads all available input directly from the active terminal without blocking.
- Returns:
The input read.
- Return type:
Important
Synchronized with
lock_tty()
.Note
Currently works on UNIX only, returns
None
on any other platform or when there is no active terminal.
- term_image.utils.write_tty(data)[source]#
Writes to the active terminal and waits until complete transmission.
- Parameters:
data (bytes) – Data to be written.
Important
Synchronized with
lock_tty()
.Note
Currently works on UNIX only, returns
None
on any other platform or when there is no active terminal.
Planned Features#
In no particular order:
Support for more terminal graphics protocols (See #23#23)
More text-based render styles (See #57#57)
Support for terminal emulators with less colors (See #61#61)
Support for terminal emulators without Unicode support (See #58#58, #60#60)
Support for fbTerm
Support for open file objects
Determination of frame duration per frame during animations and image iteration
Asynchronous animation rendering
Kitty image ID (See #40#40)
Kitty native animation (See #40#40)
Image zoom and pan functionalities
Image trimming
Specify key to end animation
Drawing images to an alternate output
Source images from raw pixel data
IPython Extension
and much more…
Known Issues#
Drawing of images and animations doesn’t work completely well with Python for Windows (tested in Windows Terminal and MinTTY).
Description: Some lines of the image seem to extend beyond the number of columns that they should normally occupy by one or two columns.
This behaviour causes animations to go bizarre when lines extend beyond the width of the terminal emulator.
Comment: First of all, the issue seems to caused by the layer between Python and the terminal emulators (i.e the PTY implementation in use) which “consumes” the escape sequences used to display images.
It is neither a fault of this library nor of the terminal emulators, as drawing of images and animations works properly with WSL within Windows Terminal.
Solution: A workaround is to leave some columns between the right edge of the image and the right edge of the terminal.
Animations with the kitty render style on the Kitty terminal emulator might be glitchy for some images with high resolution and size and/or sparse color distribution.
Description: When the LINES render method is used, lines of the image might intermittently disappear. When the WHOLE render method is used, the entire image might intermitently disappear.
Comment: This is due to the fact that drawing each frame requires clearing the previous frame off the screen, since the terminal would otherwise blend subsequent frames. Not clearing previous frames would break transparent animations and result in a performance lag that gets worse over time.
Solution: Plans are in motion to implement support for native animations i.e utilizing the animation features provided by the protocol (See #40#40).
FAQs#
- Why?
Why not?
To improve and extend the capabilities of CLI and TUI applications.
Terminals emulators have always been and always will be!
- What about Windows support?
Only the new Windows Terminal seems to have proper ANSI support and mordern terminal emulator features.
Drawing images and animations doesn’t work completely well with Python for Windows. See Known Issues.
If stuck on Windows and want to use all features, you could use WSL + Windows Terminal.
- Why are colours not properly reproduced?
Some terminals support 24-bit colors but have a 256-color pallete. This limits color reproduction.
- Why are images out of scale?
If Auto Cell Ratio is supported and enabled, call
enable_win_size_swap()
. If this doesn’t work, then open an issue here with adequate details.Otherwise, adjust the cell ratio using
set_cell_ratio()
.
- Why does my program get garbage input (possibly also written to the screen) or phantom keystrokes?
This is most definitely due to slow reponse of the terminal emulator to Terminal Queries.
To resolve this, set a higher timeout using
set_query_timeout()
. The default isDEFAULT_QUERY_TIMEOUT
seconds.You can also disable terminal queries using
disable_queries()
but note that this disables certain features.
Glossary#
Below are definitions of terms used across the API, exception messages and the documentation.
Note
For contributors, some of these terms are also used in the source code, as variable names, in comments, docstrings, etc.
- active terminal#
The terminal emulator connected to the first TTY device discovered upon loading the
term_image
package.At times, this may also be used to refer to the TTY device itself.
See also
- alignment#
The position of a primary render output within its padding.
See also
- alpha threshold#
Alpha ratio/value above which a pixel is taken as opaque (applies only to Text-based Render Styles).
See also
- animated#
Having multiple frames.
The frames of an animated image are generally meant to be displayed in rapid succession, to give the effect of animation.
- automatic size#
- automatic sizing#
A form of sizing wherein an image’s size is computed based on a combination of a frame size, the image’s original size and a given width or height.
This form of sizing tries to preserve image aspect ratio and can be used with both fixed sizing and dynamic sizing.
See also
manual sizing,
Size
,size
andset_size()
- cell ratio#
The aspect ratio (i.e the ratio of width to height) of a character cell on a terminal screen.
See also
- descendant#
Refers to an attribute, property or setting set on a class which applies to that class and all its subclasses on which the attribute, property or setting is unset.
- dynamic size#
- dynamic sizing#
A form of sizing wherein the image size is automatically computed at render-time.
This only works with automatic sizing.
See also
fixed sizing and
size
- fixed size#
- fixed sizing#
A form of sizing wherein the image size is set to a specific value which won’t change until it is re-set.
This works with both manual sizing and automatic sizing.
See also
dynamic sizing,
set_size()
,width
andheight
- frame height#
The height of the area used in automatic sizing.
- frame size#
The dimensions of the area used in automatic sizing.
- frame width#
The width of the area used in automatic sizing.
- horizontal alignment#
The horizontal position of a primary render output within its padding width.
See also
- manual size#
- manual sizing#
A form of sizing wherein both the width and the height are specified to set the image size.
This form of sizing does not preserve image aspect ratio and can only be used with fixed sizing.
See also
- padding#
Amount of lines and columns within which to fit a primary render output.
See also
- padding height#
Amount of lines within which to fit a primary render output.
Excess lines on either or both sides of the render output (depending on the vertical alignment) will be filled with spaces.
See also
- padding width#
Amount of columns within which to fit a primary render output.
Excess columns on either or both sides of the render output (depending on the horizontal alignment) will be filled with spaces.
See also
- pixel ratio#
The aspect ratio with which one rendered pixel is drawn/displayed on the terminal screen.
For Graphics-based Render Styles, this is ideally
1.0
.For Text-based Render Styles, this is equivalent to the cell ratio multiplied by 2, since there are technically two times more pixels along the vertical axis than along the horizontal axis in one character cell.
- render#
- rendered#
- rendering#
The process of encoding pixel data into a byte/character string (possibly including escape sequences to reproduce colour and transparency).
This string is also called the primary render output and excludes padding.
- render method#
- render methods#
A unique implementation of a render style.
See also
- render style#
- render styles#
- style#
- styles#
A specific technique for rendering or displaying pixel data (including images) in a terminal emulator.
A render style (or simply style) is implemented by a class, often referred to as a render style class (or simply style class).
See also
- rendered height#
The amount of lines that’ll be occupied by a primary render output when drawn (written) onto a terminal screen.
- rendered size#
The amount of space (columns and lines) that’ll be occupied by a primary render output when drawn (written) onto a terminal screen.
- rendered width#
The amount of columns that’ll be occupied by a primary render output when drawn (written) onto a terminal screen.
- source#
The resource from which an image instance is initialized.
See also
source
andsource_type
- terminal height#
The amount of lines on a terminal screen at a time i.e without scrolling.
- terminal size#
The amount of columns and lines on a terminal screen at a time i.e without scrolling.
- terminal width#
The amount of columns on a terminal screen at a time.
- vertical alignment#
The vertical position of a primary render output within its padding height.
See also