Image¶
Graphical content of arbitrary size.
Usage¶
An image can be constructed from a wide range of sources
:
from pathlib import Path
import toga
# Load an image in the same folder as the file that declares the App class
my_image = toga.Image("brutus.png")
# Load an image at an absolute path
my_image = toga.Image(Path.home() / "path/to/brutus.png")
# Create an image from raw data
with (Path.home() / "path/to/brutus.png").open("rb") as f:
my_image = toga.Image(data=f.read())
# Create an image from a PIL image (if PIL is installed)
import PIL.Image
my_pil_image = PIL.Image.new("L", (30, 30))
my_toga_image = toga.Image(my_pil_image)
You can also tell Toga how to convert from (and to) other classes that represent images via image format plugins.
Notes¶
PNG and JPEG formats are guaranteed to be supported. Other formats are available on some platforms:
GTK: BMP
macOS: GIF, BMP, TIFF
Windows: GIF, BMP, TIFF
The native platform representations for images are:
Android:
android.graphics.Bitmap
GTK:
GdkPixbuf.Pixbuf
iOS:
UIImage
macOS:
NSImage
Windows:
System.Drawing.Image
Reference¶
-
type ImageContent¶
When specifying content for an
Image
, you can provide:a string specifying an absolute or relative path to a file in a known image format;
an absolute or relative
pathlib.Path
object describing a file in a known image format;a “blob of bytes” data type (
bytes
,bytearray
, ormemoryview
) containing raw image data in a known image format;an instance of
toga.Image
;if Pillow is installed, an instance of
PIL.Image.Image
;an image of a class registered via an image format plugin (or a subclass of such a class); or
an instance of the native platform image representation.
If a relative path is provided, it will be anchored relative to the module that defines your Toga application class.
- class toga.Image(src=NOT_PROVIDED, *, path=NOT_PROVIDED, data=NOT_PROVIDED)¶
Create a new image.
- Parameters:
src (ImageContent) – The source from which to load the image. Can be any valid
image content
type.path – DEPRECATED - Use
src
.data – DEPRECATED - Use
src
.
- Raises:
FileNotFoundError – If a path is provided, but that path does not exist.
ValueError – If the source cannot be loaded as an image.
- as_format(format)¶
Return the image, converted to the image format specified.
- Parameters:
format (type[ImageT]) – Format to provide. Defaults to
Image
; also supportsPIL.Image.Image
if Pillow is installed, as well as any image types defined by installed image format plugins.- Returns:
The image in the requested format
- Raises:
TypeError – If the format supplied is not recognized.
- Return type:
ImageT
- save(path)¶
Save image to given path.
The file format of the saved image will be determined by the extension of the filename provided (e.g
path/to/mypicture.png
will save a PNG file).