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:
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[source]#
Bases:
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[source]#
Bases:
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 direct-color colour escape sequences. |
|
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:
- Returns:
A new instance.
- Raises:
TypeError – filepath is of an inappropriate type.
FileNotFoundError – The given path does not exist.
- Return type:
Propagates exceptions raised (or propagated) by
PIL.Image.open()
and 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:
Can be
a positive integer; horizontal dimension of the image, in columns.
a
Size
enum member.
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:
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:
TextImage
A render style using unicode half blocks and direct-color colour escape sequences.
See
TextImage
for the description of the constructor.
- class term_image.image.GraphicsImage(image, *, width=None, height=None)[source]#
Bases:
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:
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.
TermImageUserWarning
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:
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).