Core Library Definitions
The term_image.image
subpackage defines the following:
Convenience Functions
These functions automatically detect the best supported render style for the current terminal.
Since all classes define a common interface, any operation supported by one image class can be performed on any other image class, except stated otherwise.
- term_image.image.AutoImage(image, *, width=None, height=None, scale=(1.0, 1.0))
Convenience function for creating an image instance from a PIL image instance.
- Returns
An instance of a subclass of
BaseImage
.- Return type
Same arguments and raised exceptions as the
BaseImage
class constructor.
- term_image.image.from_file(filepath, **kwargs)
Convenience function for creating an image instance from an image file.
- Returns
An instance of a subclass of
BaseImage
.- Return type
Same arguments and raised exceptions as
BaseImage.from_file()
.
- term_image.image.from_url(url, **kwargs)
Convenience function for creating an image instance from an image URL.
- Returns
An instance of a subclass of
BaseImage
.- Return type
Same arguments and raised exceptions as
BaseImage.from_url()
.
Image Classes
Class Hierachy:
- class term_image.image.ImageSource(value)
Bases:
enum.Enum
Image source type.
Note
The values of the enumeration members are implementation details and might change at anytime. Any comparison should be by identity of the members themselves.
- FILE_PATH = <hidden>
The instance was derived from a path to a local image file.
- PIL_IMAGE = <hidden>
The instance was derived from a PIL image instance.
- URL = <hidden>
The instance was derived from an image URL.
Note
It’s allowed to set properties for animated images on non-animated ones, the values are simply ignored.
- class term_image.image.BaseImage(image, *, width=None, height=None, scale=(1.0, 1.0))
Bases:
abc.ABC
Base of all render styles.
- Parameters
image (PIL.Image.Image) – Source image.
width (Optional[int]) – Horizontal dimension of the image, in columns.
height (Optional[int]) – Vertical dimension of the image, in lines.
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
width or height is the exact number of columns or lines that’ll be used to draw the image (assuming the scale equal 1), regardless of the currently set font ratio.
If neither is given or both are
None
, the size is automatically determined when the image is to be rendered, such that it optimally fits into the terminal.The image size is multiplied by the scale on respective axes before the image is rendered.
For animated images, the seek position is initialized to the current seek position of the given image.
Attention
This class cannot be directly instantiated. Image instances should be created from its subclasses.
- property closed
Instance finalization status
- Return type
bool
- property frame_duration
Duration (in seconds) of a single frame for animated images
Setting this on non-animated images is simply ignored, no exception is raised.
- Return type
float
- property height
The unscaled height of the image.
None
when the image size is unset.Settable values:
None
: Sets the image size to an automatically calculated one, based on the current terminal size.A positive
int
: Sets the image height to the given value and the width proportionally.
- Return type
int
- property original_size
Size of the source image (in pixels)
- property n_frames: int
The number of frames in the image
- Return type
int
- property rendered_height
The scaled height of the image.
Also the exact number of lines that the drawn image will occupy in a terminal.
- Return type
int
- 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.
- Return type
Tuple[int, int]
- property rendered_width
The scaled width of the image.
Also the exact number of columns that the drawn image will occupy in a terminal.
- Return type
int
- property scale
Image scale
Settable values are:
A scale value; sets both axes.
A
tuple
of two scale values; sets(x, y)
respectively.
A scale value is a
float
in the range 0.0 < value <= 1.0.- Return type
Tuple[float, float]
- property scale_x
Horizontal scale
A scale value is a
float
in the range 0.0 < x <= 1.0.- Return type
float
- property scale_y
Vertical scale
A scale value is a
float
in the range 0.0 < y <= 1.0.- Return type
float
- property size
The unscaled size of the image.
None
when the image size is unset.Setting this to
None
unsets the image size (so that it’s automatically calculated whenever the image is rendered) and resets the recognized advanced sizing options to their defaults.This is multiplied by the scale on respective axes before the image is rendered.
- Return type
Tuple[int, int]
- property source
The source from which the instance was initialized.
- Return type
Union[PIL.Image.Image, str]
- property width
The unscaled width of the image.
None
when the image size is unset.Settable values:
None
: Sets the image size to an automatically calculated one, based on the current terminal size.A positive
int
: Sets the image width to the given value and the height proportionally.
- Return type
int
- close()
Finalizes the instance and releases external resources.
In most cases, it’s not neccesary to explicity call this method, as it’s automatically called when the instance is garbage-collected.
This method can be safely called mutiple times.
If the instance was initialized with a PIL image, the PIL image is never finalized.
- 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)
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
:and the image size is set, allows the image’s rendered height to be greater than the available terminal height.
and the image size is unset, the image is drawn to fit the terminal width.
animate (bool) – If
False
, disable animation i.e draw only the current frame of an animated image.repeat (int) – The number of times to go over all frames of an animated image. A negative value implies infinite repetition.
cached (Union[bool, int]) –
Determines if rendered frames of an animated image will be cached (for speed up of subsequent renders of the same frame) or not.
If
bool
, it directly sets if the frames will be cached or not.If
int
, caching is enabled only if the framecount of the image is less than or equal to the given number.
check_size (bool) – If
False
, does not perform size validation for non-animations.style (Any) – Style-specific 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 image.
ValueError – Image size or scale too small.
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 directly used to set the image size, the values of the fit_to_width, h_allow and v_allow arguments (whenset_size()
was called) are taken into consideration during size validation, with fit_to_width applying to only non-animations.If the size was set via another means or the size is unset, the default values of those parameters are used.
If the image size was set with the fit_to_width parameter of
set_size()
set toTrue
, then setting scroll is unnecessary.animate, repeat and cached apply to animated images only. They are simply ignored for non-animated images.
For animations (i.e animated images with animate set to
True
):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 Ctrl+C (
SIGINT
), raisingKeyboardInterrupt
.
- classmethod from_file(filepath, **kwargs)
Creates an instance from an image file.
- Parameters
filepath (str) – Relative/Absolute path to an image file.
kwargs (Union[None, int, Tuple[float, float]]) – Same keyword arguments as the class constructor.
- Returns
A new instance.
- Raises
TypeError – filepath is not a string.
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)
Creates an instance from an image URL.
- Parameters
url (str) – URL of an image file.
kwargs (Union[None, int, Tuple[float, float]]) – Same keyword arguments as the class constructor.
- 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 image file, but only after a successful initialization.
Proper clean-up is guaranteed except maybe in very rare cases.
To ensure 100% guarantee of clean-up, use the object as a context manager.
- abstract classmethod is_supported()
Returns
True
if the render style or graphics protocol implemented by the invoking class is supported by the active terminal. Otherwise,False
.Attention
Support checks for most (if not all) render styles require querying the active terminal, though only the first time they’re executed.
Hence, it’s advisable to perform all neccesary support checks (call
is_supported()
on required subclasses) at an early stage of a program, before user input is required.
- seek(pos)
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)
Sets the render method used by the instances of subclasses providing multiple render methods.
- Parameters
method (Optional[str]) – 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 the subclasses that implement such for their specific usage.
If called via:
a class, sets the class-wide render method.
an instance, sets the instance-specific render method.
If method is
None
and this method is called via:a class, the class-wide render method is reset to the default.
an instance, the instance-specific render method is removed, so that it uses the class-wide render method thenceforth.
Any instance without a specific 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.
- set_size(width=None, height=None, h_allow=0, v_allow=2, *, maxsize=None, fit_to_width=False, fit_to_height=False)
Sets the image size with extended control.
- Parameters
width (Optional[int]) – Horizontal dimension of the image, in columns.
height (Optional[int]) – Vertical dimension of the image, in lines.
h_allow (int) – Horizontal allowance i.e minimum number of columns to leave unused.
v_allow (int) – Vertical allowance i.e minimum number of lines to leave unused.
maxsize (Optional[Tuple[int, int]]) – If given, as
(columns, lines)
, it’s used instead of the terminal size.fit_to_width (bool) – Only used with automatic sizing. See description below.
fit_to_height (bool) – Only used with automatic sizing. See description below.
- Raises
TypeError – An argument is of an inappropriate type.
ValueError – An argument is of an appropriate type but has an unexpected/invalid value.
ValueError – Both width and height are specified.
ValueError – fit_to_width or fit_to_height is
True
when width, height or maxsize is given.ValueError – The available size is too small for automatic sizing.
term_image.exceptions.InvalidSizeError – maxsize is given and the resulting size will not fit into it.
If neither width nor height is given or anyone given is
None
, automatic sizing applies. In such a case, if:both fit_to_width and fit_to_height are
False
, the size is set to fit within the available terminal size (or maxsize, if given).fit_to_width is
True
, the size is set such that the rendered width is exactly the available terminal width (assuming the horizontal scale equals 1), regardless of the font ratio.fit_to_height is
True
, the size is set such that the rendered height is exactly the available terminal height (assuming the vertical scale equals 1), regardless of the font ratio.
Important
fit_to_width and fit_to_height are mutually exclusive. Only one can be
True
at a time.Neither fit_to_width nor fit_to_height may be
True
when width, height or maxsize is given.Be careful when setting fit_to_height to
True
as it might result in the image’s rendered width being larger than the terminal width (or maxsize[0]) becausedraw()
will (by default) raiseterm_image.exceptions.InvalidSizeError
if such is the case.
Vertical allowance does not apply when fit_to_width isTrue
.horizontal allowance does not apply when fit_to_height isTrue
.Allowances are ignored when maxsize is given.
fit_to_width might be set to
True
to set the image size for vertically-oriented images (i.e images with height > width) such that the drawn image spans more columns but the terminal window has to be scrolled to view the entire image.Image formatting and all size validation recognize and respect the values of the fit_to_width, h_allow and v_allow parameters, until the size is re-set or unset.
fit_to_height is only provided for completeness, it should probably be used only when the image will not be drawn to the current terminal. The value of this parameter is not recognized by any other method or operation.
Note
The size is checked to fit in only when maxsize is given along with 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.
- tell()
Returns the current image frame number.
- class term_image.image.GraphicsImage(image, **kwargs)
Bases:
term_image.image.common.BaseImage
Base of all render styles using terminal graphics protocols.
- 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.
- class term_image.image.TextImage(image, *, width=None, height=None, scale=(1.0, 1.0))
Bases:
term_image.image.common.BaseImage
Base of all render styles using ASCII/Unicode symbols [with ANSI color codes].
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))
Bases:
term_image.image.common.TextImage
A render style using unicode half blocks and ANSI 24-bit colour escape codes.
See
TextImage
for the description of the constructor.- classmethod is_supported()
Returns
True
if the render style or graphics protocol implemented by the invoking class is supported by the active terminal. Otherwise,False
.Attention
Support checks for most (if not all) render styles require querying the active terminal, though only the first time they’re executed.
Hence, it’s advisable to perform all neccesary support checks (call
is_supported()
on required subclasses) at an early stage of a program, before user input is required.
- class term_image.image.ITerm2Image(image, **kwargs)
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.Format Specification
See Image Format Specification.
[method] [ m {0 | 1} ] [ c {0-9} ]
method
: Render method override.Can be one of:
L
: LINES render method (current frame only, for animated images).W
: WHOLE render method (current frame only, for animated images).N
: Native animation. Ignored when used with non-animated images, WEBP images orImageIterator
.
Default: Current effective render method of the image.
m
: Cell content inter-mix policy (Only supported in WezTerm, ignored otherwise).If the character after
m
is:0
, contents of cells in the region covered by the image will be erased.1
, the opposite, thereby allowing existing cell contents to show under transparent areas of the image.
If absent, defaults to
m0
.e.g
m0
,m1
.
c
: ZLIB compression level, for images re-encoded in PNG format.1 -> best speed, 9 -> best compression, 0 -> no compression.
This results in a trade-off between render time and data size/draw speed.
If absent, defaults to
c4
.e.g
c0
,c9
.
- JPEG_QUALITY: int = -1
x < 0
, JPEG encoding is disabled.0 <= x <= 95
, JPEG encoding is used, with the specified quality, for most non-transparent renders (at the cost of image quality).
Only applies when not reading directly from file.
By default, images are encoded in the PNG format (when not reading directly from file) but in some cases, higher compression might be desired. Also, JPEG encoding is significantly faster and can be useful to improve non-native animation performance.
Hint
The transparency status of some images can not be correctly determined in an efficient way at render time. To ensure the JPEG format is always used for a re-encoded render, disable transparency or set a background color.
- NATIVE_ANIM_MAXSIZE: int = 2097152
Maximum size (in bytes) of image data for native animation.
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.This value can be altered but should be done with caution to avoid excessive memory usage.
- READ_FROM_FILE: bool = True
True
, image data is read directly from file when possible and no image manipulation is required.False
, images are always loaded and re-encoded, in the PNG format by default.
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.
Note
This setting does not affect animations, native animations are always read from file when possible and frames of non-native animations have to be loaded and re-encoded.
- draw(*args, method=None, mix=False, compress=4, native=False, stall_native=True, **kwargs)
Draws an image to standard output.
Extends the common interface with style-specific parameters.
- Parameters
args – Positional arguments passed up the inheritance chain.
method (Optional[str]) – Render method override. If
None
or not given, the current effective render method of the instance is used.mix (bool) –
Cell content inter-mix policy (Only supported in WezTerm, ignored otherwise). If:
False
, contents of cells within the region covered by the image are erased.True
, the opposite, thereby allowing existing text or image pixels to show under transparent areas of the image.
compress (int) –
ZLIB compression level, for images re-encoded in PNG format.
An integer between 0 and 9: 1 -> best speed, 9 -> best compression, 0 -> no compression. This results in a trade-off between render time and data size/draw speed.
native (bool) –
If
True
, use native animation (if supported).Ignored for non-animations.
animate must be
True
.alpha, repeat, cached and style do not apply.
Always loops infinitely.
No control over frame duration.
Not all animated image formats are supported e.g WEBP.
The limitations of the WHOLE render method also apply.
Normal restrictions for rendered/padding height of animations do not apply.
stall_native (bool) –
Native animation execution control. If:
True
, block untilSIGINT
(Ctrl+C) is recieved.False
, return as soon as the image is transmitted.
kwargs – Keyword arguments passed up the inheritance chain.
- Raises
term_image.exceptions.ITerm2ImageError – Native animation is not supported.
See the
draw()
method of the parent classes for full details, including the description of other parameters.
- classmethod is_supported()
Returns
True
if the render style or graphics protocol implemented by the invoking class is supported by the active terminal. Otherwise,False
.Attention
Support checks for most (if not all) render styles require querying the active terminal, though only the first time they’re executed.
Hence, it’s advisable to perform all neccesary support checks (call
is_supported()
on required subclasses) at an early stage of a program, before user input is required.
- class term_image.image.KittyImage(image, **kwargs)
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.Format Specification
See Image Format Specification.
[method] [ z [index] ] [ m {0 | 1} ] [ c {0-9} ]
method
: Render method override.Can be one of:
L
: 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
: Image/Text stacking order.index
: Image z-index. An integer in the signed 32-bit range.Images drawn in the same location with different z-index values will be blended if they are semi-transparent. If
index
is:>= 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 color.
z
withoutindex
is currently only used internally.If absent, defaults to
z0
i.e z-index zero.e.g
z0
,z1
,z-1
,z2147483647
,z-2147483648
.
m
: Image/Text inter-mixing policy.If the character after
m
is:0
, text within the region covered by the image will be erased, though text can be inter-mixed with the image after it’s been drawn.1
, text within the region covered by the image will NOT be erased.
If absent, defaults to
m0
.e.g
m0
,m1
.
c
: ZLIB compression level.1 -> best speed, 9 -> best compression, 0 -> no compression.
This results in a trade-off between render time and data size/draw speed.
If absent, defaults to
c4
.e.g
c0
,c9
.
- draw(*args, method=None, z_index=0, mix=False, compress=4, **kwargs)
Draws an image to standard output.
Extends the common interface with style-specific parameters.
- Parameters
args – Positional arguments passed up the inheritance chain.
method (Optional[str]) – Render method override. If
None
or not given, the current effective render method of the instance is used.z_index (Optional[int]) –
The stacking order of images and text for non-animations.
Images drawn in the same location with different z-index values will be blended if they are semi-transparent. If z_index is:
>= 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 color.None
, internal use only, mentioned for the sake of completeness.
To inter-mixing text with an image, see the mix parameter.
mix (bool) –
Image/Text inter-mixing policy for non-animations. If:
True
, text within the region covered by the image will NOT be erased.False
, text within the region covered by the image will be erased, though text can be inter-mixed with the image after it’s been drawn.
compress (int) –
ZLIB compression level.
An integer between 0 and 9: 1 -> best speed, 9 -> best compression, 0 -> no compression. This results in a trade-off between render time and data size/draw speed.
kwargs – Keyword arguments passed up the inheritance chain.
See the
draw()
method of the parent classes for full details, including the description of other parameters.
- classmethod is_supported()
Returns
True
if the render style or graphics protocol implemented by the invoking class is supported by the active terminal. Otherwise,False
.Attention
Support checks for most (if not all) render styles require querying the active terminal, though only the first time they’re executed.
Hence, it’s advisable to perform all neccesary support checks (call
is_supported()
on required subclasses) at an early stage of a program, before user input is required.
- class term_image.image.TermImage(*args, **kwargs)
Bases:
term_image.image.block.BlockImage
Deprecated since version 0.4.0: Replaced by
BlockImage
.
- class term_image.image.ImageIterator(image, repeat=- 1, format='', cached=100)
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 (str) – The format specifier to be used to format the rendered frames (default: auto).
cached (Union[bool, int]) –
Determines if the rendered frames will be cached (for speed up of subsequent renders) or not.
If
bool
, it directly sets if the frames will be cached or not.If
int
, caching is enabled only if the framecount of the image is less than or equal to the given number.
- 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 unset, it’s automatically calculated 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
.
- property loop_no
Iteration repeat countdown
Changes on the first iteration of each loop, except for infinite iteration where it’s always
-1
.
- close()
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)
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).
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 more surely guarantees object finalization (i.e clean-up/release of resources), especially for instances with URL sources (see BaseImage.from_url()
).
Iteration Support
Animated BaseImage
instances are iterable i.e they can be used with the for
statement (and other means of iteration such as unpacking) as in:
for frame in 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 of 1, hence caching is disabled.The frames are unformatted and transparency is enabled i.e as returned by
str(image)
.
For more extensive or custom iteration, use ImageIterator
directly.