Image file formats (2024)

The Python Imaging Library supports a wide variety of raster file formats.Over 30 different file formats can be identified and read by the library.Write support is less extensive, but most common interchange and presentationformats are supported.

The open() function identifies files from theircontents, not their names, but the save() methodlooks at the name to determine which format to use, unless the format is givenexplicitly.

When an image is opened from a file, only that instance of the image is considered tohave the format. Copies of the image will contain data loaded from the file, but notthe file itself, meaning that it can no longer be considered to be in the originalformat. So if copy() is called on an image, or another methodinternally creates a copy of the image, then any methods or attributes specific to theformat will no longer be present. The fp (file pointer) attribute will no longer bepresent, and the format attribute will be None.

Fully supported formats

BLP

BLP is the Blizzard Mipmap Format, a texture format used in World ofWarcraft. Pillow supports reading JPEG Compressed or raw BLP1images, and all types of BLP2 images.

Saving

Pillow supports writing BLP images. The save() methodcan take the following keyword arguments:

blp_version

If present and set to “BLP1”, images will be saved as BLP1. Otherwise, imageswill be saved as BLP2.

BMP

Pillow reads and writes Windows and OS/2 BMP files containing 1, L, P,or RGB data. 16-colour images are read as P images.Support for reading 8-bit run-length encoding was added in Pillow 9.1.0.Support for reading 4-bit run-length encoding was added in Pillow 9.3.0.

Opening

The open() method sets the followinginfo properties:

compression

Set to 1 if the file is a 256-color run-length encoded image.Set to 2 if the file is a 16-color run-length encoded image.

DDS

DDS is a popular container texture format used in video games and natively supportedby DirectX.

DXT1 and DXT5 pixel formats can be read, only in RGBA mode.

Added in version 3.4.0: DXT3 images can be read in RGB mode and DX10 images can be read inRGB and RGBA mode.

Added in version 6.0.0: Uncompressed RGBA images can be read.

Added in version 8.3.0: BC5S images can be opened in RGB mode, and uncompressed RGB imagescan be read. Uncompressed data can also be saved to image files.

Added in version 9.3.0: ATI1 images can be opened in L mode and ATI2 images can be opened inRGB mode.

Added in version 9.4.0: Uncompressed L (“luminance”) and LA images can be opened and saved.

Added in version 10.1.0: BC5U can be read in RGB mode, and 8-bit color indexed images can be readin P mode.

DIB

Pillow reads and writes DIB files. DIB files are similar to BMP files, so seeabove for more information.

Added in version 6.0.0.

EPS

Pillow identifies EPS files containing image data, and can read files thatcontain embedded raster images (ImageData descriptors). If Ghostscript isavailable, other EPS files can be read as well. The EPS driver can also writeEPS images. The EPS driver can read EPS images in L, LAB, RGB andCMYK mode, but Ghostscript may convert the images to RGB mode ratherthan leaving them in the original color space. The EPS driver can write imagesin L, RGB and CMYK modes.

Loading

To use Ghostscript, Pillow searches for the “gs” executable. On Windows, italso searches for “gswin32c” and “gswin64c”. To customise this behaviour,EpsImagePlugin.gs_binary = "gswin64" will set the name of the executable touse. EpsImagePlugin.gs_binary = False will prevent Ghostscript use.

If Ghostscript is available, you can call the load()method with the following parameters to affect how Ghostscript renders the EPS.

scale

Affects the scale of the resultant rasterized image. If the EPS suggeststhat the image be rendered at 100px x 100px, setting this parameter to2 will make the Ghostscript render a 200px x 200px image instead. Therelative position of the bounding box is maintained:

im = Image.open(...)im.size # (100,100)im.load(scale=2)im.size # (200,200)
transparency

If true, generates an RGBA image with a transparent background, instead ofthe default behaviour of an RGB image with a white background.

GIF

Pillow reads GIF87a and GIF89a versions of the GIF file format. The librarywrites files in GIF87a by default, unless GIF89a features are used or GIF89a isalready in use. Files are written with LZW encoding.

GIF files are initially read as grayscale (L) or palette mode (P)images. Seeking to later frames in a P image will change the image toRGB (or RGBA if the first frame had transparency).

P mode images are changed to RGB because each frame of a GIF may containits own individual palette of up to 256 colors. When a new frame is placed onto aprevious frame, those colors may combine to exceed the P mode limit of 256colors. Instead, the image is converted to RGB handle this.

If you would prefer the first P image frame to be RGB as well, so thatevery P frame is converted to RGB or RGBA mode, there is a settingavailable:

from PIL import GifImagePluginGifImagePlugin.LOADING_STRATEGY = GifImagePlugin.LoadingStrategy.RGB_ALWAYS

GIF frames do not always contain individual palettes however. If there is onlya global palette, then all of the colors can fit within P mode. If you wouldprefer the frames to be kept as P in that case, there is also a settingavailable:

from PIL import GifImagePluginGifImagePlugin.LOADING_STRATEGY = GifImagePlugin.LoadingStrategy.RGB_AFTER_DIFFERENT_PALETTE_ONLY

To restore the default behavior, where P mode images are only converted toRGB or RGBA after the first frame:

from PIL import GifImagePluginGifImagePlugin.LOADING_STRATEGY = GifImagePlugin.LoadingStrategy.RGB_AFTER_FIRST

Opening

The open() method sets the followinginfo properties:

background

Default background color (a palette color index).

transparency

Transparency color index. This key is omitted if the image is nottransparent.

version

Version (either GIF87a or GIF89a).

duration

May not be present. The time to display the current frameof the GIF, in milliseconds.

loop

May not be present. The number of times the GIF should loop. 0 means thatit will loop forever.

comment

May not be present. A comment about the image. This is the last comment foundbefore the current frame’s image.

extension

May not be present. Contains application specific information.

Reading sequences

The GIF loader supports the seek() andtell() methods. You can combine these methodsto seek to the next frame (im.seek(im.tell() + 1)).

im.seek() raises an EOFError if you try to seek after the last frame.

Saving

When calling save() to write a GIF file, thefollowing options are available:

im.save(out, save_all=True, append_images=[im1, im2, ...])
save_all

If present and true, all frames of the image will be saved. Ifnot, then only the first frame of a multiframe image will be saved.

append_images

A list of images to append as additional frames. Each of theimages in the list can be single or multiframe images.This is currently supported for GIF, PDF, PNG, TIFF, and WebP.

It is also supported for ICO and ICNS. If images are passed in of relevantsizes, they will be used instead of scaling down the main image.

include_color_table

Whether or not to include local color table.

interlace

Whether or not the image is interlaced. By default, it is, unless the imageis less than 16 pixels in width or height.

disposal

Indicates the way in which the graphic is to be treated after being displayed.

  • 0 - No disposal specified.

  • 1 - Do not dispose.

  • 2 - Restore to background color.

  • 3 - Restore to previous content.

Pass a single integer for a constant disposal, or a list or tupleto set the disposal for each frame separately.

palette

Use the specified palette for the saved image. The palette shouldbe a bytes or bytearray object containing the palette entries inRGBRGB… form. It should be no more than 768 bytes. Alternately,the palette can be passed in as anPIL.ImagePalette.ImagePalette object.

optimize

Whether to attempt to compress the palette by eliminating unused colors(this is only useful if the palette can be compressed to the next smallerpower of 2 elements) and whether to mark all pixels that are not new in thenext frame as transparent.

This is attempted by default, unless a palette is specified as an option oras part of the first image’s info dictionary.

Note that if the image you are saving comes from an existing GIF, it may havethe following properties in its info dictionary.For these options, if you do not pass them in, they will default totheir info values.

transparency

Transparency color index.

duration

The display duration of each frame of the multiframe gif, inmilliseconds. Pass a single integer for a constant duration, or alist or tuple to set the duration for each frame separately.

loop

Integer number of times the GIF should loop. 0 means that it will loopforever. If omitted or None, the image will not loop.

comment

A comment about the image.

Reading local images

The GIF loader creates an image memory the same size as the GIF file’s logicalscreen size, and pastes the actual pixel data (the local image) into thisimage. If you only want the actual pixel rectangle, you can crop the image:

im = Image.open(...)if im.tile[0][0] == "gif": # only read the first "local image" from this GIF file box = im.tile[0][1] im = im.crop(box)

ICNS

Pillow reads and writes macOS .icns files. By default, thelargest available icon is read, though you can override this by setting thesize property before callingload(). The open() methodsets the following info property:

Note

Prior to version 8.3.0, Pillow could only write ICNS files on macOS.

sizes

A list of supported sizes found in this icon file; these are a3-tuple, (width, height, scale), where scale is 2 for a retinaicon and 1 for a standard icon. You are permitted to use this 3-tupleformat for the size property if you set itbefore calling load(); after loading, the sizewill be reset to a 2-tuple containing pixel dimensions (so, e.g. if youask for (512, 512, 2), the final value ofsize will be (1024, 1024)).

Saving

The save() method can take the following keyword arguments:

append_images

A list of images to replace the scaled down versions of the image.The order of the images does not matter, as their use is determined bythe size of each image.

Added in version 5.1.0.

ICO

ICO is used to store icons on Windows. The largest available icon is read.

Saving

The save() method supports the following options:

sizes

A list of sizes including in this ico file; these are a 2-tuple,(width, height); Default to [(16, 16), (24, 24), (32, 32), (48, 48),(64, 64), (128, 128), (256, 256)]. Any sizes bigger than the originalsize or 256 will be ignored.

The save() method can take the following keyword arguments:

append_images

A list of images to replace the scaled down versions of the image.The order of the images does not matter, as their use is determined bythe size of each image.

Added in version 8.1.0.

bitmap_format

By default, the image data will be saved in PNG format. With a bitmap format of“bmp”, image data will be saved in BMP format instead.

Added in version 8.3.0.

IM

IM is a format used by LabEye and other applications based on the IFUNC imageprocessing library. The library reads and writes most uncompressed interchangeversions of this format.

IM is the only format that can store all internal Pillow formats.

JPEG

Pillow reads JPEG, JFIF, and Adobe JPEG files containing L, RGB, orCMYK data. It writes standard and progressive JFIF files.

Using the draft() method, you can speed things up byconverting RGB images to L, and resize images to 1/2, 1/4 or 1/8 oftheir original size while loading them.

By default Pillow doesn’t allow loading of truncated JPEG files, setImageFile.LOAD_TRUNCATED_IMAGES to override this.

Opening

The open() method may set the followinginfo properties if available:

jfif

JFIF application marker found. If the file is not a JFIF file, this key isnot present.

jfif_version

A tuple representing the jfif version, (major version, minor version).

jfif_density

A tuple representing the pixel density of the image, in units specifiedby jfif_unit.

jfif_unit

Units for the jfif_density:

  • 0 - No Units

  • 1 - Pixels per Inch

  • 2 - Pixels per Centimeter

dpi

A tuple representing the reported pixel density in pixels per inch, ifthe file is a jfif file and the units are in inches.

adobe

Adobe application marker found. If the file is not an Adobe JPEG file, thiskey is not present.

adobe_transform

Vendor Specific Tag.

progression

Indicates that this is a progressive JPEG file.

icc_profile

The ICC color profile for the image.

exif

Raw EXIF data from the image.

comment

A comment about the image.

Added in version 7.1.0.

Saving

The save() method supports the following options:

quality

The image quality, on a scale from 0 (worst) to 95 (best), or the stringkeep. The default is 75. Values above 95 should be avoided; 100 disablesportions of the JPEG compression algorithm, and results in large files withhardly any gain in image quality. The value keep is only valid for JPEGfiles and will retain the original image quality level, subsampling, andqtables.

optimize

If present and true, indicates that the encoder should make an extra passover the image in order to select optimal encoder settings.

progressive

If present and true, indicates that this image should be stored as aprogressive JPEG file.

dpi

A tuple of integers representing the pixel density, (x,y).

icc_profile

If present and true, the image is stored with the provided ICC profile.If this parameter is not provided, the image will be saved with no profileattached. To preserve the existing profile:

im.save(filename, 'jpeg', icc_profile=im.info.get('icc_profile'))
exif

If present, the image will be stored with the provided raw EXIF data.

keep_rgb

By default, libjpeg converts images with an RGB color space to YCbCr.If this option is present and true, those images will be stored as RGBinstead.

When this option is enabled, attempting to chroma-subsample RGB imageswith the subsampling option will raise an OSError.

Added in version 10.2.0.

subsampling

If present, sets the subsampling for the encoder.

  • keep: Only valid for JPEG files, will retain the original image setting.

  • 4:4:4, 4:2:2, 4:2:0: Specific sampling values

  • 0: equivalent to 4:4:4

  • 1: equivalent to 4:2:2

  • 2: equivalent to 4:2:0

If absent, the setting will be determined by libjpeg or libjpeg-turbo.

restart_marker_blocks

If present, emit a restart marker whenever the specified number of MCUblocks has been produced.

Added in version 10.2.0.

restart_marker_rows

If present, emit a restart marker whenever the specified number of MCUrows has been produced.

Added in version 10.2.0.

qtables

If present, sets the qtables for the encoder. This is listed as anadvanced option for wizards in the JPEG documentation. Use withcaution. qtables can be one of several types of values:

  • a string, naming a preset, e.g. keep, web_low, or web_high

  • a list, tuple, or dictionary (with integer keys =range(len(keys))) of lists of 64 integers. There must bebetween 2 and 4 tables.

Added in version 2.5.0.

streamtype

Allows storing images without quantization and Huffman tables, or withthese tables but without image data. This is useful for container formatsor network protocols that handle tables separately and share them betweenimages.

  • 0 (default): interchange datastream, with tables and image data

  • 1: abbreviated table specification (tables-only) datastream

    Added in version 10.2.0.

  • 2: abbreviated image (image-only) datastream

comment

A comment about the image.

Added in version 9.4.0.

Note

To enable JPEG support, you need to build and install the IJG JPEG librarybefore building the Python Imaging Library. See the distribution README fordetails.

JPEG 2000

Added in version 2.4.0.

Pillow reads and writes JPEG 2000 files containing L, LA, RGB,RGBA, or YCbCr data. When reading, YCbCr data is converted toRGB or RGBA depending on whether or not there is an alpha channel.Beginning with version 8.3.0, Pillow can read (but not write) RGB,RGBA, and YCbCr images with subsampled components. Pillow supportsJPEG 2000 raw codestreams (.j2k files), as well as boxed JPEG 2000 files(.jp2 or .jpx files).

When loading, if you set the mode on the image prior to theload() method being invoked, you can ask Pillow toconvert the image to either RGB or RGBA rather than choosing foritself. It is also possible to set reduce to the number of resolutions todiscard (each one reduces the size of the resulting image by a factor of 2),and layers to specify the number of quality layers to load.

Saving

The save() method supports the following options:

offset

The image offset, as a tuple of integers, e.g. (16, 16)

tile_offset

The tile offset, again as a 2-tuple of integers.

tile_size

The tile size as a 2-tuple. If not specified, or if set to None, theimage will be saved without tiling.

quality_mode

Either "rates" or "dB" depending on the units you want to use tospecify image quality.

quality_layers

A sequence of numbers, each of which represents either an approximate sizereduction (if quality mode is "rates") or a signal to noise ratio valuein decibels. If not specified, defaults to a single layer of full quality.

num_resolutions

The number of different image resolutions to be stored (which correspondsto the number of Discrete Wavelet Transform decompositions plus one).

codeblock_size

The code-block size as a 2-tuple. Minimum size is 4 x 4, maximum is 1024 x1024, with the additional restriction that no code-block may have morethan 4096 coefficients (i.e. the product of the two numbers must be nogreater than 4096).

precinct_size

The precinct size as a 2-tuple. Must be a power of two along both axes,and must be greater than the code-block size.

irreversible

If True, use the lossy discrete waveform transformation DWT 9-7.Defaults to False, which uses the lossless DWT 5-3.

mct

If 1 then enable multiple component transformation when encoding,otherwise use 0 for no component transformation (default). If MCT isenabled and irreversible is True then the Irreversible ColorTransformation will be applied, otherwise encoding will use theReversible Color Transformation. MCT works best with a mode ofRGB and is only applicable when the image data has 3 components.

Added in version 9.1.0.

progression

Controls the progression order; must be one of "LRCP", "RLCP","RPCL", "PCRL", "CPRL". The letters stand for Component,Position, Resolution and Layer respectively and control the order ofencoding, the idea being that e.g. an image encoded using LRCP mode canhave its quality layers decoded as they arrive at the decoder, while oneencoded using RLCP mode will have increasing resolutions decoded as theyarrive, and so on.

signed

If true, then tell the encoder to save the image as signed.

Added in version 9.4.0.

cinema_mode

Set the encoder to produce output compliant with the digital cinemaspecifications. The options here are "no" (the default),"cinema2k-24" for 24fps 2K, "cinema2k-48" for 48fps 2K, and"cinema4k-24" for 24fps 4K. Note that for compliant 2K files,at least one of your image dimensions must match 2048 x 1080, whilefor compliant 4K files, at least one of the dimensions must match4096 x 2160.

no_jp2

If True then don’t wrap the raw codestream in the JP2 file format whensaving, otherwise the extension of the filename will be used to determinethe format (default).

Added in version 9.1.0.

comment

Adds a custom comment to the file, replacing the default“Created by OpenJPEG version” comment.

Added in version 9.5.0.

plt

If True and OpenJPEG 2.4.0 or later is available, then include a PLT(packet length, tile-part header) marker in the produced file.Defaults to False.

Added in version 9.5.0.

Note

To enable JPEG 2000 support, you need to build and install the OpenJPEGlibrary, version 2.0.0 or higher, before building the Python ImagingLibrary.

Windows users can install the OpenJPEG binaries available on theOpenJPEG website, but must add them to their PATH in order to use Pillow (ifyou fail to do this, you will get errors about not being able to load the_imaging DLL).

MSP

Pillow identifies and reads MSP files from Windows 1 and 2. The library writesuncompressed (Windows 1) versions of this format.

PCX

Pillow reads and writes PCX files containing 1, L, P, or RGB data.

PFM

Added in version 10.3.0.

Pillow reads and writes grayscale (Pf format) Portable FloatMap (PFM) filescontaining F data.

Color (PF format) PFM files are not supported.

Opening

The open() function sets the followinginfo properties:

scale

The absolute value of the number stored in the Scale Factor / Endianness line.

PNG

Pillow identifies, reads, and writes PNG files containing 1, L, LA,I, P, RGB or RGBA data. Interlaced files are supported as ofv1.1.7.

As of Pillow 6.0, EXIF data can be read from PNG images. However, unlike otherimage formats, EXIF data is not guaranteed to be present ininfo until load() has beencalled.

By default Pillow doesn’t allow loading of truncated PNG files, setImageFile.LOAD_TRUNCATED_IMAGES to override this.

Opening

The open() function sets the followinginfo properties, when appropriate:

chromaticity

The chromaticity points, as an 8 tuple of floats. (White PointX, White Point Y, Red X, Red Y, Green X, GreenY, Blue X, Blue Y)

gamma

Gamma, given as a floating point number.

srgb

The sRGB rendering intent as an integer.

  • 0 Perceptual

  • 1 Relative Colorimetric

  • 2 Saturation

  • 3 Absolute Colorimetric

transparency

For P images: Either the palette index for full transparent pixels,or a byte string with alpha values for each palette entry.

For 1, L, I and RGB images, the color that representsfull transparent pixels in this image.

This key is omitted if the image is not a transparent palette image.

open also sets Image.text to a dictionary of the values of thetEXt, zTXt, and iTXt chunks of the PNG image. Individualcompressed chunks are limited to a decompressed size ofPngImagePlugin.MAX_TEXT_CHUNK, by default 1MB, to preventdecompression bombs. Additionally, the total size of all of the textchunks is limited to PngImagePlugin.MAX_TEXT_MEMORY, defaulting to64MB.

Saving

The save() method supports the following options:

optimize

If present and true, instructs the PNG writer to make the output file assmall as possible. This includes extra processing in order to find optimalencoder settings.

transparency

For P, 1, L, I, and RGB images, this option controlswhat color from the image to mark as transparent.

For P images, this can be a either the palette index,or a byte string with alpha values for each palette entry.

dpi

A tuple of two numbers corresponding to the desired dpi in each direction.

pnginfo

A PIL.PngImagePlugin.PngInfo instance containing chunks.

compress_level

ZLIB compression level, a number between 0 and 9: 1 gives best speed,9 gives best compression, 0 gives no compression at all. Default is 6.When optimize option is True compress_level has no effect(it is set to 9 regardless of a value passed).

icc_profile

The ICC Profile to include in the saved file.

exif

The exif data to include in the saved file.

Added in version 6.0.0.

bits (experimental)

For P images, this option controls how many bits to store. If omitted,the PNG writer uses 8 bits (256 colors).

dictionary (experimental)

Set the ZLIB encoder dictionary.

Note

To enable PNG support, you need to build and install the ZLIB compressionlibrary before building the Python Imaging Library. See theinstallation documentation for details.

APNG sequences

The PNG loader includes limited support for reading and writing Animated PortableNetwork Graphics (APNG) files.When an APNG file is loaded, get_format_mimetype()will return "image/apng". The value of the is_animatedproperty will be True when the n_frames property isgreater than 1. For APNG files, the n_frames property depends on both the animationframe count as well as the presence or absence of a default image. See thedefault_image property documentation below for more details.The seek() and tell() methodsare supported.

im.seek() raises an EOFError if you try to seek after the last frame.

These info properties will be set for APNG frames,where applicable:

default_image

Specifies whether or not this APNG file contains a separate default image,which is not a part of the actual APNG animation.

When an APNG file contains a default image, the initially loaded image (i.e.the result of seek(0)) will be the default image.To account for the presence of the default image, then_frames property will be set to frame_count + 1,where frame_count is the actual APNG animation frame count.To load the first APNG animation frame, seek(1) must be called.

  • True - The APNG contains default image, which is not an animation frame.

  • False - The APNG does not contain a default image. The n_frames propertywill be set to the actual APNG animation frame count.The initially loaded image (i.e. seek(0)) will be the first APNG animationframe.

loop

The number of times to loop this APNG, 0 indicates infinite looping.

duration

The time to display this APNG frame (in milliseconds).

Note

The APNG loader returns images the same size as the APNG file’s logical screen size.The returned image contains the pixel data for a given frame, after applyingany APNG frame disposal and frame blend operations (i.e. it contains what a webbrowser would render for this frame - the composite of all previous frames and thisframe).

Any APNG file containing sequence errors is treated as an invalid image. The APNGloader will not attempt to repair and reorder files containing sequence errors.

Saving

When calling save(), by default only a single frame PNG filewill be saved. To save an APNG file (including a single frame APNG), the save_allparameter must be set to True. The following parameters can also be set:

default_image

Boolean value, specifying whether or not the base image is a default image.If True, the base image will be used as the default image, and the first imagefrom the append_images sequence will be the first APNG animation frame.If False, the base image will be used as the first APNG animation frame.Defaults to False.

append_images

A list or tuple of images to append as additional frames. Each of theimages in the list can be single or multiframe images. The size of each frameshould match the size of the base image. Also note that if a frame’s mode doesnot match that of the base image, the frame will be converted to the base imagemode.

loop

Integer number of times to loop this APNG, 0 indicates infinite looping.Defaults to 0.

duration

Integer (or list or tuple of integers) length of time to display this APNG frame(in milliseconds).Defaults to 0.

disposal

An integer (or list or tuple of integers) specifying the APNG disposaloperation to be used for this frame before rendering the next frame.Defaults to 0.

  • 0 (OP_NONE, default) -No disposal is done on this frame before rendering the next frame.

  • 1 (PIL.PngImagePlugin.Disposal.OP_BACKGROUND) -This frame’s modified region is cleared to fully transparent black beforerendering the next frame.

  • 2 (OP_PREVIOUS) -This frame’s modified region is reverted to the previous frame’s contents beforerendering the next frame.

blend

An integer (or list or tuple of integers) specifying the APNG blendoperation to be used for this frame before rendering the next frame.Defaults to 0.

  • 0 (OP_SOURCE) -All color components of this frame, including alpha, overwrite the previous outputimage contents.

  • 1 (OP_OVER) -This frame should be alpha composited with the previous output image contents.

Note

The duration, disposal and blend parameters can be set to lists or tuples tospecify values for each individual frame in the animation. The length of the list or tuplemust be identical to the total number of actual frames in the APNG animation.If the APNG contains a default image (i.e. default_image is set to True),these list or tuple parameters should not include an entry for the default image.

PPM

Pillow reads and writes PBM, PGM, PPM and PNM files containing 1, L, I orRGB data.

“Raw” (P4 to P6) formats can be read, and are used when writing.

Since Pillow 9.2.0, “plain” (P1 to P3) formats can be read as well.

SGI

Pillow reads and writes uncompressed L, RGB, and RGBA files.

SPIDER

Pillow reads and writes SPIDER image files of 32-bit floating point data(“F;32F”).

Pillow also reads SPIDER stack files containing sequences of SPIDER images. Theseek() and tell() methods are supported, andrandom access is allowed.

Opening

The open() method sets the following attributes:

format

Set to SPIDER

istack

Set to 1 if the file is an image stack, else 0.

n_frames

Set to the number of images in the stack.

A convenience method, convert2byte(),is provided for converting floating point data to byte data (mode L):

im = Image.open("image001.spi").convert2byte()

Saving

The extension of SPIDER files may be any 3 alphanumeric characters. Thereforethe output format must be specified explicitly:

im.save('newimage.spi', format='SPIDER')

For more information about the SPIDER image processing package, seehttps://github.com/spider-em/SPIDER

TGA

Pillow reads and writes TGA images containing L, LA, P,RGB, and RGBA data. Pillow can read and write both uncompressed andrun-length encoded TGAs.

Saving

The save() method can take the following keyword arguments:

compression

If set to “tga_rle”, the file will be run-length encoded.

Added in version 5.3.0.

id_section

The identification field.

Added in version 5.3.0.

orientation

If present and a positive number, the first pixel is for the top left corner,rather than the bottom left corner.

Added in version 5.3.0.

TIFF

Pillow reads and writes TIFF files. It can read both striped and tiledimages, pixel and plane interleaved multi-band images. If you havelibtiff and its headers installed, Pillow can read and write many kindsof compressed TIFF files. If not, Pillow will only read and writeuncompressed files.

Note

Beginning in version 5.0.0, Pillow requires libtiff to read orwrite compressed files. Prior to that release, Pillow had buggysupport for reading Packbits, LZW and JPEG compressed TIFFswithout using libtiff.

Opening

The open() method sets the followinginfo properties:

compression

Compression mode.

Added in version 2.0.0.

dpi

Image resolution as an (xdpi, ydpi) tuple, where applicable. You can usethe tag attribute to get moredetailed information about the image resolution.

Added in version 1.1.5.

resolution

Image resolution as an (xres, yres) tuple, where applicable. This is ameasurement in whichever unit is specified by the file.

Added in version 1.1.5.

The tag_v2 attribute contains adictionary of TIFF metadata. The keys are numerical indexes fromTiffTags.TAGS_V2. Values are strings or numbers for singleitems, multiple values are returned in a tuple of values. Rationalnumbers are returned as a IFDRationalobject.

Added in version 3.0.0.

For compatibility with legacy code, thetag attribute contains a dictionaryof decoded TIFF fields as returned prior to version 3.0.0. Values arereturned as either strings or tuples of numeric values. Rationalnumbers are returned as a tuple of (numerator, denominator).

Deprecated since version 3.0.0.

Reading Multi-frame TIFF Images

The TIFF loader supports the seek() andtell() methods, taking and returning frame numberswithin the image file. You can combine these methods to seek to the next frame(im.seek(im.tell() + 1)). Frames are numbered from 0 to im.n_frames - 1,and can be accessed in any order.

im.seek() raises an EOFError if you try to seek after thelast frame.

Saving

The save() method can take the following keyword arguments:

save_all

If true, Pillow will save all frames of the image to a multiframe tiff document.

Added in version 3.4.0.

append_images

A list of images to append as additional frames. Each of theimages in the list can be single or multiframe images. Note however, that forcorrect results, all the appended images should have the sameencoderinfo and encoderconfig properties.

Added in version 4.2.0.

tiffinfo

A ImageFileDirectory_v2 object or dictobject containing tiff tags and values. The TIFF field type isautodetected for Numeric and string values, any other typesrequire using an ImageFileDirectory_v2object and setting the type intagtype withthe appropriate numerical value fromTiffTags.TYPES.

Added in version 2.3.0.

Metadata values that are of the rational type should be passed inusing a IFDRational object.

Added in version 3.1.0.

For compatibility with legacy code, aImageFileDirectory_v1 object maybe passed in this field. However, this is deprecated.

Added in version 5.4.0.

Previous versions only supported some tags when writing usinglibtiff. The supported list is found inTiffTags.LIBTIFF_CORE.

Added in version 6.1.0.

Added support for signed types (e.g. TIFF_SIGNED_LONG) and multiple values.Multiple values for a single tag must be toImageFileDirectory_v2 as a tuple andrequire a matching type intagtype tagtype.

exif

Alternate keyword to “tiffinfo”, for consistency with other formats.

Added in version 8.4.0.

compression

A string containing the desired compression method for thefile. (valid only with libtiff installed) Valid compressionmethods are: None, "group3", "group4", "jpeg", "lzma","packbits", "tiff_adobe_deflate", "tiff_ccitt", "tiff_lzw","tiff_raw_16", "tiff_sgilog", "tiff_sgilog24", "tiff_thunderscan","webp", "zstd"

quality

The image quality for JPEG compression, on a scale from 0 (worst) to 100(best). The default is 75.

Added in version 6.1.0.

These arguments to set the tiff header fields are an alternative tousing the general tags available through tiffinfo.

description

software

date_time

artist

copyright

Strings

icc_profile

The ICC Profile to include in the saved file.

resolution_unit

An integer. 1 for no unit, 2 for inches and 3 for centimeters.

resolution

Either an integer or a float, used for both the x and y resolution.

x_resolution

Either an integer or a float.

y_resolution

Either an integer or a float.

dpi

A tuple of (x_resolution, y_resolution), with inches as the resolutionunit. For consistency with other image formats, the x and y resolutionsof the dpi will be rounded to the nearest integer.

WebP

Pillow reads and writes WebP files. The specifics of Pillow’s capabilities withthis format are currently undocumented.

Saving

The save() method supports the following options:

lossless

If present and true, instructs the WebP writer to use lossless compression.

quality

Integer, 0-100, defaults to 80. For lossy, 0 gives the smallestsize and 100 the largest. For lossless, this parameter is the amountof effort put into the compression: 0 is the fastest, but gives largerfiles compared to the slowest, but best, 100.

alpha_quality

Integer, 0-100, defaults to 100. For lossy compression only. 0 gives thesmallest size and 100 is lossless.

method

Quality/speed trade-off (0=fast, 6=slower-better). Defaults to 4.

exact

If true, preserve the transparent RGB values. Otherwise, discardinvisible RGB values for better compression. Defaults to false.Requires libwebp 0.5.0 or later.

icc_profile

The ICC Profile to include in the saved file. Only supported ifthe system WebP library was built with webpmux support.

exif

The exif data to include in the saved file. Only supported ifthe system WebP library was built with webpmux support.

xmp

The XMP data to include in the saved file. Only supported ifthe system WebP library was built with webpmux support.

Saving sequences

Note

Support for animated WebP files will only be enabled if the system WebPlibrary is v0.5.0 or later. You can check webp animation support atruntime by calling features.check("webp_anim").

When calling save() to write a WebP file, by defaultonly the first frame of a multiframe image will be saved. If the save_allargument is present and true, then all frames will be saved, and the followingoptions will also be available.

append_images

A list of images to append as additional frames. Each of theimages in the list can be single or multiframe images.

duration

The display duration of each frame, in milliseconds. Pass a singleinteger for a constant duration, or a list or tuple to set theduration for each frame separately.

loop

Number of times to repeat the animation. Defaults to [0 = infinite].

background

Background color of the canvas, as an RGBA tuple with values inthe range of (0-255).

minimize_size

If true, minimize the output size (slow). Implicitly disableskey-frame insertion.

kmin, kmax

Minimum and maximum distance between consecutive key frames inthe output. The library may insert some key frames as neededto satisfy this criteria. Note that these conditions shouldhold: kmax > kmin and kmin >= kmax / 2 + 1. Also, if kmax <= 0,then key-frame insertion is disabled; and if kmax == 1, then allframes will be key-frames (kmin value does not matter for thesespecial cases).

allow_mixed

If true, use mixed compression mode; the encoder heuristicallychooses between lossy and lossless for each frame.

XBM

Pillow reads and writes X bitmap files (mode 1).

Read-only formats

CUR

CUR is used to store cursors on Windows. The CUR decoder reads the largestavailable cursor. Animated cursors are not supported.

DCX

DCX is a container file format for PCX files, defined by Intel. The DCX formatis commonly used in fax applications. The DCX decoder can read files containing1, L, P, or RGB data.

When the file is opened, only the first image is read. You can useseek() or ImageSequence to read other images.

FITS

Added in version 9.1.0.

Pillow identifies and reads FITS files, commonly used for astronomy. Uncompressed andGZIP_1 compressed images can be read.

FLI, FLC

Pillow reads Autodesk FLI and FLC animations.

The open() method sets the followinginfo properties:

duration

The delay (in milliseconds) between each frame.

FPX

Pillow reads Kodak FlashPix files. Only the highest resolution image is read from thefile, and the viewing transform is not taken into account.

To enable FPX support, you must install olefile.

Note

To enable full FlashPix support, you need to build and install the IJG JPEGlibrary before building the Python Imaging Library. See the distributionREADME for details.

FTEX

Added in version 3.2.0.

The FTEX decoder reads textures used for 3D objects inIndependence War 2: Edge Of Chaos. The plugin reads a single textureper file, in the compressed and uncompressed formats.

GBR

The GBR decoder reads GIMP brush files, version 1 and 2.

Opening

The open() method sets the followinginfo properties:

comment

The brush name.

spacing

The spacing between the brushes, in pixels. Version 2 only.

GD

Pillow reads uncompressed GD2 files. Note that you must usePIL.GdImageFile.open() to read such a file.

Opening

The open() method sets the followinginfo properties:

transparency

Transparency color index. This key is omitted if the image is nottransparent.

IMT

Pillow reads Image Tools images containing L data.

IPTC/NAA

Pillow provides limited read support for IPTC/NAA newsphoto files.

MCIDAS

Pillow identifies and reads 8-bit McIdas area files.

MIC

Pillow identifies and reads Microsoft Image Composer (MIC) files. When opened,the first sprite in the file is loaded. You can use seek() andtell() to read other sprites from the file.

Note that there may be an embedded gamma of 2.2 in MIC files.

To enable MIC support, you must install olefile.

MPO

Pillow identifies and reads Multi Picture Object (MPO) files, loading the primaryimage when first opened. The seek() and tell()methods may be used to read other pictures from the file. The pictures arezero-indexed and random access is supported.

Saving

When calling save() to write an MPO file, by defaultonly the first frame of a multiframe image will be saved. If the save_allargument is present and true, then all frames will be saved, and the followingoption will also be available.

append_images

A list of images to append as additional pictures. Each of theimages in the list can be single or multiframe images.

Added in version 9.3.0.

PCD

Pillow reads PhotoCD files containing RGB data. This only reads the 768x512resolution image from the file. Higher resolutions are encoded in a proprietaryencoding.

PIXAR

Pillow provides limited support for PIXAR raster files. The library canidentify and read “dumped” RGB files.

The format code is PIXAR.

PSD

Pillow identifies and reads PSD files written by Adobe Photoshop 2.5 and 3.0.

QOI

Added in version 9.5.0.

Pillow reads images in Quite OK Image format using a Python decoder. If you wish towrite code specifically for this format, qoi is an alternative library thatuses C to decode the image and interfaces with NumPy.

SUN

Pillow identifies and reads Sun raster files.

WAL

Added in version 1.1.4.

Pillow reads Quake2 WAL texture files.

Note that this file format cannot be automatically identified, so you must usethe open function in the WalImageFile module to read files inthis format.

By default, a Quake2 standard palette is attached to the texture. To overridethe palette, use the PIL.Image.Image.putpalette() method.

WMF, EMF

Pillow can identify WMF and EMF files.

On Windows, it can read WMF and EMF files. By default, it will load the imageat 72 dpi. To load it at another resolution:

from PIL import Imagewith Image.open("drawing.wmf") as im: im.load(dpi=144)

To add other read or write support, usePIL.WmfImagePlugin.register_handler() to register a WMF and EMFhandler.

from PIL import Imagefrom PIL import WmfImagePluginclass WmfHandler: def open(self, im): ... def load(self, im): ... return image def save(self, im, fp, filename): ...wmf_handler = WmfHandler()WmfImagePlugin.register_handler(wmf_handler)im = Image.open("sample.wmf")

XPM

Pillow reads X pixmap files (mode P) with 256 colors or less.

Opening

The open() method sets the followinginfo properties:

transparency

Transparency color index. This key is omitted if the image is nottransparent.

Write-only formats

PALM

Pillow provides write-only support for PALM pixmap files.

The format code is Palm, the extension is .palm.

PDF

Pillow can write PDF (Acrobat) images. Such images are written as binary PDF 1.4files. Different encoding methods are used, depending on the image mode.

  • 1 mode images are saved using TIFF encoding, or JPEG encoding if libtiff support isunavailable

  • L, RGB and CMYK mode images use JPEG encoding

  • P mode images use HEX encoding

  • LA and RGBA mode images use JPEG2000 encoding

Saving

The save() method can take the following keyword arguments:

save_all

If a multiframe image is used, by default, only the first image will be saved.To save all frames, each frame to a separate page of the PDF, the save_allparameter must be present and set to True.

Added in version 3.0.0.

append_images

A list of PIL.Image.Image objects to append as additional pages. Eachof the images in the list can be single or multiframe images. The save_allparameter must be present and set to True in conjunction withappend_images.

Added in version 4.2.0.

append

Set to True to append pages to an existing PDF file. If the file doesn’texist, an OSError will be raised.

Added in version 5.1.0.

resolution

Image resolution in DPI. This, together with the number of pixels in theimage, will determine the physical dimensions of the page that will besaved in the PDF.

dpi

A tuple of (x_resolution, y_resolution), with inches as the resolutionunit. If both the resolution parameter and the dpi parameter arepresent, resolution will be ignored.

title

The document’s title. If not appending to an existing PDF file, this willdefault to the filename.

Added in version 5.1.0.

author

The name of the person who created the document.

Added in version 5.1.0.

subject

The subject of the document.

Added in version 5.1.0.

keywords

Keywords associated with the document.

Added in version 5.1.0.

creator

If the document was converted to PDF from another format, the name of theconforming product that created the original document from which it wasconverted.

Added in version 5.1.0.

producer

If the document was converted to PDF from another format, the name of theconforming product that converted it to PDF.

Added in version 5.1.0.

creationDate

The creation date of the document. If not appending to an existing PDFfile, this will default to the current time.

Added in version 5.3.0.

modDate

The modification date of the document. If not appending to an existing PDFfile, this will default to the current time.

Added in version 5.3.0.

XV Thumbnails

Pillow can read XV thumbnail files.

Identify-only formats

BUFR

Added in version 1.1.3.

Pillow provides a stub driver for BUFR files.

To add read or write support to your application, usePIL.BufrStubImagePlugin.register_handler().

GRIB

Added in version 1.1.5.

Pillow provides a stub driver for GRIB files.

The driver requires the file to start with a GRIB header. If you have fileswith embedded GRIB data, or files with multiple GRIB fields, your applicationhas to seek to the header before passing the file handle to Pillow.

To add read or write support to your application, usePIL.GribStubImagePlugin.register_handler().

HDF5

Added in version 1.1.5.

Pillow provides a stub driver for HDF5 files.

To add read or write support to your application, usePIL.Hdf5StubImagePlugin.register_handler().

MPEG

Pillow identifies MPEG files.

Image file formats (2024)
Top Articles
Windows 10 : ce sera bien fini en 2025
What Are Some Alternative Options to Foreclosure?
The Blackening Showtimes Near Century Aurora And Xd
Walgreens Boots Alliance, Inc. (WBA) Stock Price, News, Quote & History - Yahoo Finance
Ups Stores Near
Metra Union Pacific West Schedule
Noaa Charleston Wv
Phone Number For Walmart Automotive Department
Professor Qwertyson
Victoria Secret Comenity Easy Pay
Produzione mondiale di vino
Tlc Africa Deaths 2021
What Was D-Day Weegy
Fallout 4 Pipboy Upgrades
Obituary | Shawn Alexander | Russell Funeral Home, Inc.
Mini Handy 2024: Die besten Mini Smartphones | Purdroid.de
Katherine Croan Ewald
Icommerce Agent
Gayla Glenn Harris County Texas Update
Program Logistics and Property Manager - Baghdad, Iraq
Sea To Dallas Google Flights
Craigslist St. Cloud Minnesota
Discord Nuker Bot Invite
Gillette Craigslist
Nottingham Forest News Now
TMO GRC Fortworth TX | T-Mobile Community
Yayo - RimWorld Wiki
Co10 Unr
What Is Opm1 Treas 310 Deposit
Filmy Met
60 Second Burger Run Unblocked
Mg Char Grill
Lil Durk's Brother DThang Killed in Harvey, Illinois, ME Confirms
Murphy Funeral Home & Florist Inc. Obituaries
Joe's Truck Accessories Summerville South Carolina
Free Robux Without Downloading Apps
Consume Oakbrook Terrace Menu
Aveda Caramel Toner Formula
RALEY MEDICAL | Oklahoma Department of Rehabilitation Services
Shane Gillis’s Fall and Rise
Janaki Kalaganaledu Serial Today Episode Written Update
Busted Newspaper Mcpherson Kansas
Random Animal Hybrid Generator Wheel
Watch Chainsaw Man English Sub/Dub online Free on HiAnime.to
10 Types of Funeral Services, Ceremonies, and Events » US Urns Online
Tlc Africa Deaths 2021
Jigidi Free Jigsaw
Waco.craigslist
SF bay area cars & trucks "chevrolet 50" - craigslist
Vt Craiglist
Latest Posts
Article information

Author: Jeremiah Abshire

Last Updated:

Views: 6254

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Jeremiah Abshire

Birthday: 1993-09-14

Address: Apt. 425 92748 Jannie Centers, Port Nikitaville, VT 82110

Phone: +8096210939894

Job: Lead Healthcare Manager

Hobby: Watching movies, Watching movies, Knapping, LARPing, Coffee roasting, Lacemaking, Gaming

Introduction: My name is Jeremiah Abshire, I am a outstanding, kind, clever, hilarious, curious, hilarious, outstanding person who loves writing and wants to share my knowledge and understanding with you.