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.AutoImage(image, *, width=None, height=None, scale=(1.0, 1.0))[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 available size, elseFIT
.
- FIT#
The image size is set to fit optimally within the available size.
- FIT_TO_WIDTH#
The size is set such that the width is exactly the available 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 Hierachy#
The Classes#
Type of all render style 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.ImageMeta(name, bases, dict, **kwds)[source]#
Bases:
term_image.utils.ClassPropertyMeta
,abc.ABCMeta
Type of all render style classes.
Note
For all render style classes (instances of this class) defined within this package,str(cls)
yields the same value ascls.style
.For render style classes defined outside this package (subclasses of those defined within this package),str(cls)
is equivalent torepr(cls)
.Instance Properties:
Name of the render style [category].
- property style#
Name of the render style [category].
- Returns:
The name of the render style [category] implemented by the invoking class, if defined within this package (
term_image
)None
, if the invoking class is defined outside this package (term_image
)
- Type:
Optional[str]
Examples
For a class defined within this package:
>>> from term_image.image import KittyImage >>> KittyImage.style 'kitty'
For a class defined outside this package:
>>> from term_image.image import KittyImage >>> class MyImage(KittyImage): pass >>> MyImage.style is None True
Hint
Equivalent to
str(cls)
for all render style classes (instances ofImageMeta
) defined within this package.
- class term_image.image.BaseImage(image, *, width=None, height=None, scale=(1.0, 1.0))[source]#
Bases:
object
Base of all render styles.
- Parameters:
image (PIL.Image.Image) – Source image.
width (Union[int, Size, None]) –
Can be
an integer; horizontal dimension of the image, in columns.
a
Size
enum member.
height (Union[int, Size, None]) –
Can be
an integer; vertical dimension of the image, in lines.
a
Size
enum member.
scale (Tuple[float, float]) – The fraction of the size (on respective axes) to render the image with.
- Raises:
TypeError – An argument is of an inappropriate type.
ValueError – An argument 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.The image size is multiplied by the scale on respective axes when the image is rendered.
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 for animated images
The unscaled height of the image
True
if the image is animated.Size of the source image (in pixels)
The number of frames in the image
The scaled height of the image
The scaled size of the image
The scaled width of the image
Image scale
Horizontal scale
Vertical scale
The unscaled size of the image
The source from which the instance was initialized
The kind of source from which the instance was initialized
The unscaled width of the image
Class Properties:
Render style forced support status
Instance Methods:
Finalizes the instance and releases external resources.
Draws an 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 forced_support#
Render style forced support status
- Type:
- GET:
Returns the forced support status of the render style of the invoker.
- SET:
Forced support is enabled or disabled for the render style of the invoker.
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 by the base style class (
BaseImage
).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 for animated images
- Returns:
A duration (in seconds), if the image is animated.
None
, if the image is not animated.
- Type:
Optional[float]
Setting this on non-animated images is simply ignored.
- property height#
The unscaled height of the image
- Returns:
- Type:
SETTABLE VALUES:
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
.
Setting this
results in a fixed size.
resets the recognized advanced sizing options to their defaults.
- property rendered_height#
The scaled height of the image
Also the exact number of lines that the drawn image will occupy in a terminal.
- Type:
- property rendered_size#
The scaled size of the image
Also the exact number of columns and lines (respectively) that the drawn image will occupy in a terminal.
- property rendered_width#
The scaled width of the image
Also the exact number of columns that the drawn image will occupy in a terminal.
- Type:
- property scale#
Image scale
SETTABLE VALUES:
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 size#
The unscaled size of the image
- Returns:
- Type:
SETTABLE VALUES:
A
Size
enum member; the image size is set as prescibed by the enum member.
Setting this
implies dynamic sizing i.e the size is computed whenever the image is rendered.
resets the recognized advanced sizing options to their defaults.
This is multiplied by the scale on respective axes when the image is rendered.
- property source#
The source from which the instance was initialized
- Type:
Union[PIL.Image.Image, str]
- property width#
The unscaled width of the image
- Returns:
- Type:
SETTABLE VALUES:
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
.
Setting this
results in a fixed size.
resets the recognized advanced sizing options to their defaults.
- close()[source]#
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.
- 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, **style)[source]#
Draws an image to standard output.
- Parameters:
h_align (Optional[str]) – Horizontal alignment (“left” / “<”, “center” / “|” or “right” / “>”). Default: center.
pad_width (Optional[int]) –
Number of columns within which to align the image.
Excess columns are filled with spaces.
Must not be greater than the available terminal width.
Default: terminal width, minus horizontal allowance.
v_align (Optional[str]) – Vertical alignment (“top”/”^”, “middle”/”-” or “bottom”/”_”). Default: middle.
pad_height (Optional[int]) –
Number of lines within which to align the image.
Excess lines are filled with spaces.
Must not be greater than the available terminal height, for animations.
Default: terminal height, minus vertical allowance.
alpha (Optional[float, 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
.
scroll (bool) – Only applies to non-animations. If
True
, allows the image’s rendered height to be greater than the available terminal height.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.
check_size (bool) – If
False
, does not perform size validation for non-animations.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.
ValueError – Unable to convert or resize image.
term_image.exceptions.InvalidSizeError – The image’s rendered size can not fit into the available terminal size.
term_image.exceptions.StyleError – Unrecognized style-specific parameter(s).
If
set_size()
was used to set the image size, the horizontal and vertical allowances (set whenset_size()
was called) are taken into consideration during size validation. If the size was set via another means or the size is dynamic, the default allowances apply.For non-animations, if the image size was set with
FIT_TO_WIDTH
, the image height is not validated and setting scroll is unnecessary.animate, repeat and cached apply to animated images only. They are simply ignored for non-animated images.
For animations (i.e animated images with animate set to
True
):scroll is ignored.
Image size and padding height are always validated, if set or given.
with the exception of native animations provided by some render styles.
Animations, by default, are infinitely looped and can be terminated with
SIGINT
(CTRL + C
), raisingKeyboardInterrupt
.
- classmethod from_file(filepath, **kwargs)[source]#
Creates an instance from an image file.
- Parameters:
- 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 neccesary 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 – method is not a string or
None
.ValueError – the given method is not implmented by the invoking class (or class of the invoking instance).
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, h_allow=0, v_allow=2, maxsize=None)[source]#
Sets the image size with extended control.
- Parameters:
width (int | term_image.image.common.Size | None) –
Can be
an integer; horizontal dimension of the image, in columns.
a
Size
enum member.
height (int | term_image.image.common.Size | None) –
Can be
an integer; vertical dimension of the image, in lines.
a
Size
enum member.
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 (Tuple[int, int] | None) – If given, as
(columns, lines)
, it’s used instead of the terminal size.
- 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.
ValueError – The available size is too small for automatic sizing.
term_image.exceptions.InvalidSizeError – maxsize is given and the resulting size will not fit into it.
If neither width nor height is given (or both are
None
),FIT
applies.If width or height is a
Size
enum member, automatic sizing applies as prescribed by the enum member.When
FIT_TO_WIDTH
is given,size validation operations take it into consideration.
Vertical allowance is nullified.
Allowances are ignored when maxsize is given.
Render formatting and size validation operations recognize and respect the horizontal and vertical allowances, until the image size is re-set.
Note
The size is checked to fit in only when maxsize is given along with a fixed width or height because
draw()
is generally not the means of drawing such an image and all rendering methods don’t perform any sort of size validation.If the validation is not desired, specify only one of maxsize and width or height, not both.
- class term_image.image.TextImage(image, *, width=None, height=None, scale=(1.0, 1.0))[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, scale=(1.0, 1.0))[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, scale=(1.0, 1.0))[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, scale=(1.0, 1.0))[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 very slow 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 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.
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.
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
native (bool) → Native animation policy. [1]
True
→ use the protocol’s native animation featureFalse
→ use the normal animationdefault →
False
alpha, repeat, cached and style do not apply
Ignored if the image is not animated or animate is
False
Normal restrictions for sizing of animations do not apply
Uses WHOLE render method
The terminal emulator completely controls the animation
stall_native (bool) → Native animation execution control.
True
→ block untilSIGINT
(Ctrl+C) is recievedFalse
→ return as soon as the image is transmitteddefault →
True
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)N
→ Native animation [1] (ignored when used with non-animated images orImageIterator
)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 policy
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 (negative if disabled).
- 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 it’s 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 on the iterm2 render style baseclass (
ITerm2Image
).- DELETE:
The value is unset, thereby resetting it to the default.
TermImageWarning
is issued (and shown only the first time, except a filter is set to do otherwise) if the image data size for a native animation is above this value.Note
This property is descendant but is always unset for all subclasses and instances. Hence, setting/resetting it on this class, a subclass or an instance affects this class, all its subclasses and all their instances.
Warning
This property should be altered with caution to avoid excessive memory usage.
- property read_from_file#
Read-from-file optimization policy
- Type:
- GET:
Returns the effective read-from-file policy of the invoker.
- 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 it’s 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, scale=(1.0, 1.0))[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
Effeciently 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, it directly sets if the frames will be cached or not.
an 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 and scale.
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:
Changes on the first iteration of each loop, except for infinite iteration where it’s always
-1
.
- 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).