# wx.Image¶

This class encapsulates a platform-independent image.

An image can be created from data, or using wx.Bitmap.ConvertToImage . An image can be loaded from a file in a variety of formats, and is extensible to new formats via image format handlers. Functions are available to set and get image bits, so it can be used for basic image manipulation.

A wx.Image cannot (currently) be drawn directly to a wx.DC. Instead, a platform-specific wx.Bitmap object must be created from it using the Bitmap.Bitmap(wxImage,int depth) constructor. This bitmap can then be drawn in a device context, using wx.DC.DrawBitmap .

More on the difference between wx.Image and wx.Bitmap: wx.Image is just a buffer of RGB bytes with an optional buffer for the alpha bytes. It is all generic, platform independent and image file format independent code. It includes generic code for scaling, resizing, clipping, and other manipulations of the image data. OTOH, wx.Bitmap is intended to be a wrapper of whatever is the native image format that is quickest/easiest to draw to a DC or to be the target of the drawing operations performed on a wx.MemoryDC. By splitting the responsibilities between Image/wxBitmap like this then it’s easier to use generic code shared by all platforms and image types for generic operations and platform specific code where performance or compatibility is needed.

One colour value of the image may be used as a mask colour which will lead to the automatic creation of a wx.Mask object associated to the bitmap object.

## Alpha channel support¶

Starting from wxWidgets 2.5.0 wx.Image supports alpha channel data, that is in addition to a byte for the red, green and blue colour components for each pixel it also stores a byte representing the pixel opacity. An alpha value of 0 corresponds to a transparent pixel (null opacity) while a value of 255 means that the pixel is 100% opaque. The constants IMAGE_ALPHA_TRANSPARENT and IMAGE_ALPHA_OPAQUE can be used to indicate those values in a more readable form. While all images have RGB data, not all images have an alpha channel. Before using wx.Image.GetAlpha you should check if this image contains an alpha channel with wx.Image.HasAlpha . Currently the BMP, PNG, TGA, and TIFF format handlers have full alpha channel support for loading so if you want to use alpha you have to use one of these formats. If you initialize the image alpha channel yourself using wx.Image.SetAlpha , you should save it in either PNG, TGA, or TIFF format to avoid losing it as these are the only handlers that currently support saving with alpha.

## Available image handlers¶

The following image handlers are available. BMPHandler is always installed by default. To use other image formats, install the appropriate handler with wx.Image.AddHandler or call wx.InitAllImageHandlers .

When saving in PCX format, wx.PCXHandler will count the number of different colours in the image; if there are 256 or less colours, it will save as 8 bit, else it will save as 24 bit. Loading PNMs only works for ASCII or raw RGB images. When saving in PNM format, wx.PNMHandler will always save as raw RGB. Saving GIFs requires images of maximum 8 bpp (see Quantize ), and the alpha channel converted to a mask (see wx.Image.ConvertAlphaToMask ). Saving an animated GIF requires images of the same size (see wx.GIFHandler.SaveAnimation )

## Class Hierarchy¶

Inheritance diagram for class Image:

## Methods Summary¶

 __init__ Creates an empty wx.Image object without an alpha channel. AddHandler Register an image handler. AdjustChannels This function muliplies all 4 channels (red, green, blue, alpha) with Blur Blurs the image in both horizontal and vertical directions by the specified pixel blurRadius. BlurHorizontal Blurs the image in the horizontal direction only. BlurVertical Blurs the image in the vertical direction only. CanRead Returns True if at least one of the available image handlers can read the file with the given name. CleanUpHandlers Deletes all image handlers. Clear Initialize the image data with zeroes (the default) or with the byte value given as value. ClearAlpha Removes the alpha channel from the image. ComputeHistogram Computes the histogram of the image. ConvertAlphaToMask If the image has alpha channel, this method converts it to mask. ConvertToBitmap ConvertToBitmap(depth=-1) . Bitmap ConvertToDisabled Returns disabled (dimmed) version of the image. ConvertToGreyscale Returns a greyscale version of the image. ConvertToMono Returns monochromatic version of the image. ConvertToMonoBitmap ConvertToMonoBitmap(red, green, blue) . Bitmap Copy Returns an identical copy of this image. Create Creates a fresh image. Destroy Destroys the image data. FindFirstUnusedColour Finds the first colour that is never used in the image. FindHandler Finds the handler with the given name. FindHandlerMime Finds the handler associated with the given MIME type. GetAlpha Return alpha value at given pixel location. GetAlphaBuffer Returns a writable Python buffer object that is pointing at the Alpha GetBlue Returns the blue intensity at the given coordinate. GetData Returns a copy of the RGB bytes of the image. GetDataBuffer Returns a writable Python buffer object that is pointing at the RGB GetGreen Returns the green intensity at the given coordinate. GetHeight Gets the height of the image in pixels. GetImageCount If the image file contains more than one image and the image handler is capable of retrieving these individually, this function will return the number of available images. GetImageExtWildcard Iterates all registered wx.ImageHandler objects, and returns a string containing file extension masks suitable for passing to file open/save dialog boxes. GetMaskBlue Gets the blue value of the mask colour. GetMaskGreen Gets the green value of the mask colour. GetMaskRed Gets the red value of the mask colour. GetOption Gets a user-defined string-valued option. GetOptionInt Gets a user-defined integer-valued option. GetOrFindMaskColour Get the current mask colour or find a suitable unused colour that could be used as a mask colour. GetPalette Returns the palette associated with the image. GetRed Returns the red intensity at the given coordinate. GetSize Returns the size of the image in pixels. GetSubImage Returns a sub image of the current one as long as the rect belongs entirely to the image. GetType Gets the type of image found by LoadFile or specified with SaveFile . GetWidth Gets the width of the image in pixels. HSVtoRGB Converts a color in HSV color space to RGB color space. HasAlpha Returns True if this image has alpha channel, False otherwise. HasMask Returns True if there is a mask active, False otherwise. HasOption Returns True if the given option is present. InitAlpha Initializes the image alpha channel data. InitStandardHandlers Internal use only. InsertHandler Adds a handler at the start of the static list of format handlers. IsOk Returns True if image data is present. IsTransparent Returns True if the given pixel is transparent, i.e. either has the mask colour if this image has a mask or if this image has alpha channel and alpha value of this pixel is strictly less than threshold. LoadFile Loads an image from an input stream. Mirror Returns a mirrored copy of the image. Paste Copy the data of the given image to the specified position in this image. RGBtoHSV Converts a color in RGB color space to HSV color space. RemoveHandler Finds the handler with the given name, and removes it. Replace Replaces the colour specified by r1,g1,b1 by the colour r2,g2,b2. Rescale Changes the size of the image in-place by scaling it: after a call to this function,the image will have the given width and height. Resize Changes the size of the image in-place without scaling it by adding either a border with the given colour or cropping as necessary. Rotate Rotates the image about the given point, by angle radians. Rotate180 Returns a copy of the image rotated by 180 degrees. Rotate90 Returns a copy of the image rotated 90 degrees in the direction indicated by clockwise. RotateHue Rotates the hue of each pixel in the image by angle, which is a float in the range of -1.0 to +1.0, where -1.0 corresponds to -360 degrees and +1.0 corresponds to +360 degrees. SaveFile Saves an image in the given stream. Scale Returns a scaled version of the image. SetAlpha Sets the alpha value for the given pixel. SetAlphaBuffer Sets the internal image alpha pointer to point at a Python buffer SetData Sets the image data without performing checks. SetDataBuffer Sets the internal image data pointer to point at a Python buffer SetMask Specifies whether there is a mask or not. SetMaskColour Sets the mask colour for this image (and tells the image to use the mask). SetMaskFromImage Sets image’s mask so that the pixels that have RGB value of mr,mg,mb in mask will be masked in the image. SetOption Sets a user-defined option. SetPalette Associates a palette with the image. SetRGB Set the color of the pixel at the given x and y coordinate. SetType Set the type of image returned by GetType . Size Returns a resized version of this image without scaling it by adding either a border with the given colour or cropping as necessary. __bool__ __nonzero__

## Class API¶

class wx.Image(Object)

Possible constructors:

Image()

Image(width, height, clear=True)

Image(sz, clear=True)

Image(name, type=BITMAP_TYPE_ANY, index=-1)

Image(name, mimetype, index=-1)

Image(stream, type=BITMAP_TYPE_ANY, index=-1)

Image(stream, mimetype, index=-1)

Image(width, height, data)

Image(width, height, data, alpha)

Image(size, data)

Image(size, data, alpha)


This class encapsulates a platform-independent image.

### Methods¶

__init__(self, *args, **kw)

__init__ (self)

Creates an empty wx.Image object without an alpha channel.

__init__ (self, width, height, clear=True)

Creates an image with the given size and clears it if requested.

Does not create an alpha channel.

Parameters
• width (int) – Specifies the width of the image.

• height (int) – Specifies the height of the image.

• clear (bool) – If True, initialize the image to black.

__init__ (self, sz, clear=True)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
• sz (wx.Size) –

• clear (bool) –

__init__ (self, name, type=BITMAP_TYPE_ANY, index=-1)

Creates an image from a file.

Parameters
• name (string) – Name of the file from which to load the image.

• type (BitmapType) – May be one of the following:

• wx.BITMAP_TYPE_BMP: Load a Windows bitmap file.

• wx.BITMAP_TYPE_GIF: Load a GIF bitmap file.

• wx.BITMAP_TYPE_JPEG: Load a JPEG bitmap file.

• wx.BITMAP_TYPE_PNG: Load a PNG bitmap file.

• wx.BITMAP_TYPE_PCX: Load a PCX bitmap file.

• wx.BITMAP_TYPE_PNM: Load a PNM bitmap file.

• wx.BITMAP_TYPE_TIFF: Load a TIFF bitmap file.

• wx.BITMAP_TYPE_TGA: Load a TGA bitmap file.

• wx.BITMAP_TYPE_XPM: Load a XPM bitmap file.

• wx.BITMAP_TYPE_ICO: Load a Windows icon file (ICO).

• wx.BITMAP_TYPE_CUR: Load a Windows cursor file (CUR).

• wx.BITMAP_TYPE_ANI: Load a Windows animated cursor file (ANI).

• wx.BITMAP_TYPE_ANY: Will try to autodetect the format.

• index (int) – Index of the image to load in the case that the image file contains multiple images. This is only used by GIF, ICO and TIFF handlers. The default value (-1) means “choose the default image” and is interpreted as the first image (index=0) by the GIF and TIFF handler and as the largest and most colourful one by the ICO handler.

Note

Depending on how wxWidgets has been configured and by which handlers have been loaded, not all formats may be available. Any handler other than BMP must be previously initialized with wx.Image.AddHandler or InitAllImageHandlers.

Note

You can use GetOptionInt to get the hotspot when loading cursor files:

hotspot_x = image.GetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_X)
hotspot_y = image.GetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_Y)


__init__ (self, name, mimetype, index=-1)

Creates an image from a file using MIME-types to specify the type.

Parameters
• name (string) – Name of the file from which to load the image.

• mimetype (string) – MIME type string (for example ‘image/jpeg’)

• index (int) – See description in wx.Image overload.

__init__ (self, stream, type=BITMAP_TYPE_ANY, index=-1)

Creates an image from a stream.

Parameters
• stream (wx.InputStream) – Opened input stream from which to load the image. Currently, the stream must support seeking.

• type (BitmapType) – See description in wx.Image overload.

• index (int) – See description in wx.Image overload.

__init__ (self, stream, mimetype, index=-1)

Creates an image from a stream using MIME-types to specify the type.

Parameters
• stream (wx.InputStream) – Opened input stream from which to load the image. Currently, the stream must support seeking.

• mimetype (string) – MIME type string (for example ‘image/jpeg’)

• index (int) – See description in wx.Image overload.

__init__ (self, width, height, data)

Creates an image from RGB data in memory.

__init__ (self, width, height, data, alpha)

Creates an image from RGB data in memory, plus an alpha channel

__init__ (self, size, data)

Creates an image from RGB data in memory.

__init__ (self, size, data, alpha)

Creates an image from RGB data in memory, plus an alpha channel

static AddHandler(handler)

Register an image handler.

Typical example of use:

wx.Image.AddHandler(wx.PNGHandler)


See Available image handlers for a list of the available handlers. You can also use wx.InitAllImageHandlers to add handlers for all the image formats supported by wxWidgets at once.

Parameters

handler (wx.ImageHandler) – A heap-allocated handler object which will be deleted by wx.Image if it is removed later by RemoveHandler or at program shutdown.

AdjustChannels(self, factor_red, factor_green, factor_blue, factor_alpha=1.0)

This function muliplies all 4 channels (red, green, blue, alpha) with a factor (around 1.0). Useful for gamma correction, colour correction and to add a certain amount of transparency to a image (fade in fade out effects). If factor_alpha is given but the original image has no alpha channel then a alpha channel will be added.

Return type

wx.Image

Blur(self, blurRadius)

Blurs the image in both horizontal and vertical directions by the specified pixel blurRadius.

This should not be used when using a single mask colour for transparency.

Parameters

Return type

wx.Image

BlurHorizontal(self, blurRadius)

Blurs the image in the horizontal direction only.

This should not be used when using a single mask colour for transparency.

Parameters

Return type

wx.Image

BlurVertical(self, blurRadius)

Blurs the image in the vertical direction only.

This should not be used when using a single mask colour for transparency.

Parameters

Return type

wx.Image

static CanRead(*args, **kw)

Returns True if at least one of the available image handlers can read the file with the given name.

See wx.ImageHandler.CanRead for more info.

Parameters

filename (string) –

Return type

bool

Returns True if at least one of the available image handlers can read the data in the given stream.

See wx.ImageHandler.CanRead for more info.

Parameters

stream (wx.InputStream) –

Return type

bool

static CleanUpHandlers()

Deletes all image handlers.

This function is called by wxWidgets on exit.

Clear(self, value=0)

Initialize the image data with zeroes (the default) or with the byte value given as value.

Parameters

value (int) –

New in version 2.9.0.

ClearAlpha(self)

Removes the alpha channel from the image.

This function should only be called if the image has alpha channel data, use HasAlpha to check for this.

New in version 2.9.1.

ComputeHistogram(self, histogram)

Computes the histogram of the image.

histogram is a reference to wx.ImageHistogram object. wx.ImageHistogram is a specialization of HashMap “template” and is defined as follows:

# This is a raw translation of the ImageHistogramEntry
# code in C++, not a real Python class
class ImageHistogramEntry(object):

def __init__(self):

self.index = 0
self.value = 0

Parameters

histogram (wx.ImageHistogram) –

Return type

int

Returns

Returns number of colours in the histogram.

ConvertAlphaToMask(self, *args, **kw)

If the image has alpha channel, this method converts it to mask.

If the image has an alpha channel, all pixels with alpha value less than threshold are replaced with the mask colour and the alpha channel is removed. Otherwise nothing is done.

The mask colour is chosen automatically using FindFirstUnusedColour by this function, see the overload below if you this is not appropriate.

Parameters

threshold (int) –

Return type

bool

Returns

Returns True on success, False on error.

ConvertAlphaToMask (self, mr, mg, mb, threshold=IMAGE_ALPHA_THRESHOLD)

If the image has alpha channel, this method converts it to mask using the specified colour as the mask colour.

If the image has an alpha channel, all pixels with alpha value less than threshold are replaced with the mask colour and the alpha channel is removed. Otherwise nothing is done.

Parameters
• mr (int) – The red component of the mask colour.

• mg (int) – The green component of the mask colour.

• mb (int) – The blue component of the mask colour.

• threshold (int) – Pixels with alpha channel values below the given threshold are considered to be transparent, i.e. the corresponding mask pixels are set. Pixels with the alpha values above the threshold are considered to be opaque.

Return type

bool

Returns

Returns True on success, False on error.

New in version 2.9.0.

ConvertToBitmap(self, depth=-1)

Convert the image to a wx.Bitmap.

ConvertToDisabled(self, brightness=255)

Returns disabled (dimmed) version of the image.

Parameters

brightness (int) –

Return type

wx.Image

New in version 2.9.0.

ConvertToGreyscale(self, *args, **kw)

ConvertToGreyscale (self, weight_r, weight_g, weight_b)

Returns a greyscale version of the image.

The returned image uses the luminance component of the original to calculate the greyscale. Defaults to using the standard ITU-T BT.601 when converting to YUV, where every pixel equals (R weight_r) + (G weight_g) + (B weight_b).

Parameters
• weight_r (float) –

• weight_g (float) –

• weight_b (float) –

Return type

wx.Image

ConvertToGreyscale (self)

Returns a greyscale version of the image.

Return type

wx.Image

New in version 2.9.0.

ConvertToMono(self, r, g, b)

Returns monochromatic version of the image.

The returned image has white colour where the original has (r,g,b) colour and black colour everywhere else.

Parameters
• r (int) –

• g (int) –

• b (int) –

Return type

wx.Image

ConvertToMonoBitmap(self, red, green, blue)

Creates a monochrome version of the image and returns it as a wx.Bitmap.

Copy(self)

Returns an identical copy of this image.

Return type

wx.Image

Create(self, *args, **kw)

Create (self, width, height, clear=True)

Creates a fresh image.

See Image.__init__ for more info.

Parameters
• width (int) –

• height (int) –

• clear (bool) –

Return type

bool

Returns

True if the call succeeded, False otherwise.

Create (self, sz, clear=True)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
• sz (wx.Size) –

• clear (bool) –

Return type

bool

Create (self, width, height, data)

Create a new image initialized with the given RGB data.

Return type

bool

Create (self, width, height, data, alpha)

Create a new image initialized with the given RGB data and Alpha data.

Return type

bool

Create (self, size, data)

Create a new image initialized with the given RGB data.

Return type

bool

Create (self, size, data, alpha)

Create a new image initialized with the given RGB data and Alpha data.

Return type

bool

Destroy(self)

Destroys the image data.

FindFirstUnusedColour(self, startR=1, startG=0, startB=0)

Finds the first colour that is never used in the image.

The search begins at given initial colour and continues by increasing R, G and B components (in this order) by 1 until an unused colour is found or the colour space exhausted.

The parameters r, g, b are pointers to variables to save the colour.

The parameters startR, startG, startB define the initial values of the colour. The returned colour will have RGB values equal to or greater than these.

Parameters
• startR (int) –

• startG (int) –

• startB (int) –

Return type

tuple

Returns

( r, g, b )

Note

This method involves computing the histogram, which is a computationally intensive operation.

static FindHandler(*args, **kw)

FindHandler (name)

Finds the handler with the given name.

Parameters

name (string) – The handler name.

Return type

wx.ImageHandler

Returns

A pointer to the handler if found, None otherwise.

FindHandler (extension, imageType)

Finds the handler associated with the given extension and type.

Parameters
• extension (string) – The file extension, such as “bmp”.

• imageType (BitmapType) – The image type; one of the wx.BitmapType values.

Return type

wx.ImageHandler

Returns

A pointer to the handler if found, None otherwise.

FindHandler (imageType)

Finds the handler associated with the given image type.

Parameters

imageType (BitmapType) – The image type; one of the wx.BitmapType values.

Return type

wx.ImageHandler

Returns

A pointer to the handler if found, None otherwise.

static FindHandlerMime(mimetype)

Finds the handler associated with the given MIME type.

Parameters

mimetype (string) – MIME type.

Return type

wx.ImageHandler

Returns

A pointer to the handler if found, None otherwise.

GetAlpha(self, *args, **kw)

GetAlpha (self, x, y)

Return alpha value at given pixel location.

Parameters
• x (int) –

• y (int) –

Return type

int

GetAlpha (self)

Returns a copy of the Alpha bytes of the image.

Return type

PyObject

GetAlphaBuffer(self)

Returns a writable Python buffer object that is pointing at the Alpha data buffer inside the Image. You need to ensure that you do not use this buffer object after the image has been destroyed.

Return type

PyObject

GetBlue(self, x, y)

Returns the blue intensity at the given coordinate.

Parameters
• x (int) –

• y (int) –

Return type

int

GetData(self)

Returns a copy of the RGB bytes of the image.

Return type

PyObject

GetDataBuffer(self)

Returns a writable Python buffer object that is pointing at the RGB image data buffer inside the Image. You need to ensure that you do not use this buffer object after the image has been destroyed.

Return type

PyObject

GetGreen(self, x, y)

Returns the green intensity at the given coordinate.

Parameters
• x (int) –

• y (int) –

Return type

int

GetHeight(self)

Gets the height of the image in pixels.

Return type

int

static GetImageCount(*args, **kw)

If the image file contains more than one image and the image handler is capable of retrieving these individually, this function will return the number of available images.

For the overload taking the parameter filename, that’s the name of the file to query. For the overload taking the parameter stream, that’s the opened input stream with image data.

See wx.ImageHandler.GetImageCount for more info.

The parameter type may be one of the following values:

• wx.BITMAP_TYPE_BMP: Load a Windows bitmap file.

• wx.BITMAP_TYPE_GIF: Load a GIF bitmap file.

• wx.BITMAP_TYPE_JPEG: Load a JPEG bitmap file.

• wx.BITMAP_TYPE_PNG: Load a PNG bitmap file.

• wx.BITMAP_TYPE_PCX: Load a PCX bitmap file.

• wx.BITMAP_TYPE_PNM: Load a PNM bitmap file.

• wx.BITMAP_TYPE_TIFF: Load a TIFF bitmap file.

• wx.BITMAP_TYPE_TGA: Load a TGA bitmap file.

• wx.BITMAP_TYPE_XPM: Load a XPM bitmap file.

• wx.BITMAP_TYPE_ICO: Load a Windows icon file (ICO).

• wx.BITMAP_TYPE_CUR: Load a Windows cursor file (CUR).

• wx.BITMAP_TYPE_ANI: Load a Windows animated cursor file (ANI).

• wx.BITMAP_TYPE_ANY: Will try to autodetect the format.

Returns

Number of available images. For most image handlers, this is 1 (exceptions are TIFF and ICO formats as well as animated GIFs for which this function returns the number of frames in the animation).

GetImageCount (filename, type=BITMAP_TYPE_ANY)

Parameters
Return type

int

GetImageCount (stream, type=BITMAP_TYPE_ANY)

Parameters
Return type

int

static GetImageExtWildcard()

Iterates all registered wx.ImageHandler objects, and returns a string containing file extension masks suitable for passing to file open/save dialog boxes.

Return type

string

Returns

The format of the returned string is "(*.ext1;*.ext2)|*.ext1;*.ext2" . It is usually a good idea to prepend a description before passing the result to the dialog. Example:

FileDlg = wx.FileDialog(self, "Choose Image", os.getcwd(), "",
"Image Files " + wx.Image.GetImageExtWildcard(),
wx.FD_OPEN)


GetMaskBlue(self)

Gets the blue value of the mask colour.

Return type

int

GetMaskGreen(self)

Gets the green value of the mask colour.

Return type

int

GetMaskRed(self)

Gets the red value of the mask colour.

Return type

int

GetOption(self, name)

Gets a user-defined string-valued option.

Generic options:

• IMAGE_OPTION_FILENAME: The name of the file from which the image was loaded.

Options specific to wx.GIFHandler:

• IMAGE_OPTION_GIF_COMMENT: The comment text that is read from or written to the GIF file. In an animated GIF each frame can have its own comment. If there is only a comment in the first frame of a GIF it will not be repeated in other frames.

Parameters

name (string) – The name of the option, case-insensitive.

Return type

string

Returns

The value of the option or an empty string if not found. Use HasOption if an empty string can be a valid option value.

GetOptionInt(self, name)

Gets a user-defined integer-valued option.

The function is case-insensitive to name. If the given option is not present, the function returns 0. Use HasOption if 0 is a possibly valid value for the option.

Generic options:

• IMAGE_OPTION_MAX_WIDTH and IMAGE_OPTION_MAX_HEIGHT: If either of these options is specified, the loaded image will be scaled down (preserving its aspect ratio) so that its width is less than the max width given if it is not 0 and its height is less than the max height given if it is not 0. This is typically used for loading thumbnails and the advantage of using these options compared to calling Rescale after loading is that some handlers (only JPEG one right now) support rescaling the image during loading which is vastly more efficient than loading the entire huge image and rescaling it later (if these options are not supported by the handler, this is still what happens however). These options must be set before calling LoadFile to have any effect.

• IMAGE_OPTION_ORIGINAL_WIDTH and IMAGE_OPTION_ORIGINAL_HEIGHT: These options will return the original size of the image if either IMAGE_OPTION_MAX_WIDTH or IMAGE_OPTION_MAX_HEIGHT is specified.

New in version 2.9.3.

• IMAGE_OPTION_QUALITY: JPEG quality used when saving. This is an integer in 0..100 range with 0 meaning very poor and 100 excellent (but very badly compressed). This option is currently ignored for the other formats.

• IMAGE_OPTION_RESOLUTIONUNIT: The value of this option determines whether the resolution of the image is specified in centimetres or inches, see ImageResolution enum elements.

• IMAGE_OPTION_RESOLUTION , IMAGE_OPTION_RESOLUTIONX and IMAGE_OPTION_RESOLUTIONY: These options define the resolution of the image in the units corresponding to IMAGE_OPTION_RESOLUTIONUNIT options value. The first option can be set before saving the image to set both horizontal and vertical resolution to the same value. The X and Y options are set by the image handlers if they support the image resolution (currently BMP, JPEG and TIFF handlers do) and the image provides the resolution information and can be queried after loading the image.

Options specific to wx.PNGHandler:

• IMAGE_OPTION_PNG_FORMAT: Format for saving a PNG file, see ImagePNGType for the supported values.

• IMAGE_OPTION_PNG_BITDEPTH: Bit depth for every channel (R/G/B/A).

• IMAGE_OPTION_PNG_FILTER: Filter for saving a PNG file, see libpng (http://www.libpng.org/pub/png/libpng-1.2.5-manual.html) for possible values (e.g. PNG_FILTER_NONE, PNG_FILTER_SUB, PNG_FILTER_UP, etc).

• IMAGE_OPTION_PNG_COMPRESSION_LEVEL: Compression level (0..9) for saving a PNG file. An high value creates smaller-but-slower PNG file. Note that unlike other formats (e.g. JPEG) the PNG format is always lossless and thus this compression level doesn’t tradeoff the image quality.

• IMAGE_OPTION_PNG_COMPRESSION_MEM_LEVEL: Compression memory usage level (1..9) for saving a PNG file. An high value means the saving process consumes more memory, but may create smaller PNG file.

• IMAGE_OPTION_PNG_COMPRESSION_STRATEGY: Possible values are 0 for default strategy, 1 for filter, and 2 for Huffman-only. You can use OptiPNG (http://optipng.sourceforge.net/) to get a suitable value for your application.

• IMAGE_OPTION_PNG_COMPRESSION_BUFFER_SIZE: Internal buffer size (in bytes) for saving a PNG file. Ideally this should be as big as the resulting PNG file. Use this option if your application produces images with small size variation.

Options specific to wx.TIFFHandler:

• IMAGE_OPTION_TIFF_BITSPERSAMPLE: Number of bits per sample (channel). Currently values of 1 and 8 are supported. A value of 1 results in a black and white image. A value of 8 (the default) can mean greyscale or RGB, depending on the value of IMAGE_OPTION_TIFF_SAMPLESPERPIXEL .

• IMAGE_OPTION_TIFF_SAMPLESPERPIXEL: Number of samples (channels) per pixel. Currently values of 1 and 3 are supported. A value of 1 results in either a greyscale (by default) or black and white image, depending on the value of IMAGE_OPTION_TIFF_BITSPERSAMPLE . A value of 3 (the default) will result in an RGB image.

• IMAGE_OPTION_TIFF_COMPRESSION: Compression type. By default it is set to 1 (COMPRESSION_NONE). Typical other values are 5 (COMPRESSION_LZW) and 7 (COMPRESSION_JPEG). See tiff.h for more options.

• IMAGE_OPTION_TIFF_PHOTOMETRIC: Specifies the photometric interpretation. By default it is set to 2 (PHOTOMETRIC_RGB) for RGB images and 0 (PHOTOMETRIC_MINISWHITE) for greyscale or black and white images. It can also be set to 1 (PHOTOMETRIC_MINISBLACK) to treat the lowest value as black and highest as white. If you want a greyscale image it is also sufficient to only specify IMAGE_OPTION_TIFF_PHOTOMETRIC and set it to either PHOTOMETRIC_MINISWHITE or PHOTOMETRIC_MINISBLACK. The other values are taken care of.

Parameters

name (string) – The name of the option, case-insensitive.

Return type

int

Returns

The value of the option or 0 if not found. Use HasOption if 0 can be a valid option value.

Note

Be careful when combining the options IMAGE_OPTION_TIFF_SAMPLESPERPIXEL , IMAGE_OPTION_TIFF_BITSPERSAMPLE , and IMAGE_OPTION_TIFF_PHOTOMETRIC . While some measures are taken to prevent illegal combinations and/or values, it is still easy to abuse them and come up with invalid results in the form of either corrupted images or crashes.

GetOrFindMaskColour(self)

Get the current mask colour or find a suitable unused colour that could be used as a mask colour.

Returns True if the image currently has a mask.

Return type

tuple

Returns

( r, g, b )

GetPalette(self)

Returns the palette associated with the image.

Currently the palette is only used when converting to wx.Bitmap under Windows.

Some of the wx.Image handlers have been modified to set the palette if one exists in the image file (usually 256 or less colour images in GIF or PNG format).

Return type

wx.Palette

GetRed(self, x, y)

Returns the red intensity at the given coordinate.

Parameters
• x (int) –

• y (int) –

Return type

int

GetSize(self)

Returns the size of the image in pixels.

Return type

wx.Size

New in version 2.9.0.

GetSubImage(self, rect)

Returns a sub image of the current one as long as the rect belongs entirely to the image.

Parameters

rect (wx.Rect) –

Return type

wx.Image

GetType(self)

Gets the type of image found by LoadFile or specified with SaveFile .

Return type

wx.BitmapType

New in version 2.9.0.

GetWidth(self)

Gets the width of the image in pixels.

Return type

int

static HSVtoRGB(hsv)

Converts a color in HSV color space to RGB color space.

Parameters

hsv (HSVValue) –

Return type

RGBValue

HasAlpha(self)

Returns True if this image has alpha channel, False otherwise.

Return type

bool

HasMask(self)

Returns True if there is a mask active, False otherwise.

Return type

bool

HasOption(self, name)

Returns True if the given option is present.

The function is case-insensitive to name.

The lists of the currently supported options are in GetOption and GetOptionInt function docs.

Parameters

name (string) –

Return type

bool

InitAlpha(self)

Initializes the image alpha channel data.

It is an error to call it if the image already has alpha data. If it doesn’t, alpha data will be by default initialized to all pixels being fully opaque. But if the image has a mask colour, all mask pixels will be completely transparent.

static InitStandardHandlers()

Internal use only.

Adds standard image format handlers. It only install BMPHandler for the time being, which is used by wx.Bitmap.

This function is called by wxWidgets on startup, and shouldn’t be called by the user.

static InsertHandler(handler)

Adds a handler at the start of the static list of format handlers.

Parameters

handler (wx.ImageHandler) – A new image format handler object. There is usually only one instance of a given handler class in an application session.

IsOk(self)

Returns True if image data is present.

Return type

bool

IsTransparent(self, x, y, threshold=IMAGE_ALPHA_THRESHOLD)

Returns True if the given pixel is transparent, i.e. either has the mask colour if this image has a mask or if this image has alpha channel and alpha value of this pixel is strictly less than threshold.

Parameters
• x (int) –

• y (int) –

• threshold (int) –

Return type

bool

LoadFile(self, *args, **kw)

Loads an image from an input stream.

Parameters
• stream (wx.InputStream) – Opened input stream from which to load the image. Currently, the stream must support seeking.

• type (BitmapType) – May be one of the following:

• wx.BITMAP_TYPE_BMP: Load a Windows bitmap file.

• wx.BITMAP_TYPE_GIF: Load a GIF bitmap file.

• wx.BITMAP_TYPE_JPEG: Load a JPEG bitmap file.

• wx.BITMAP_TYPE_PNG: Load a PNG bitmap file.

• wx.BITMAP_TYPE_PCX: Load a PCX bitmap file.

• wx.BITMAP_TYPE_PNM: Load a PNM bitmap file.

• wx.BITMAP_TYPE_TIFF: Load a TIFF bitmap file.

• wx.BITMAP_TYPE_TGA: Load a TGA bitmap file.

• wx.BITMAP_TYPE_XPM: Load a XPM bitmap file.

• wx.BITMAP_TYPE_ICO: Load a Windows icon file (ICO).

• wx.BITMAP_TYPE_CUR: Load a Windows cursor file (CUR).

• wx.BITMAP_TYPE_ANI: Load a Windows animated cursor file (ANI).

• wx.BITMAP_TYPE_ANY: Will try to autodetect the format.

• index (int) – Index of the image to load in the case that the image file contains multiple images. This is only used by GIF, ICO and TIFF handlers. The default value (-1) means “choose the default image” and is interpreted as the first image (index=0) by the GIF and TIFF handler and as the largest and most colourful one by the ICO handler.

Return type

bool

Returns

True if the operation succeeded, False otherwise. If the optional index parameter is out of range, False is returned and a call to wx.LogError takes place.

Note

Depending on how wxWidgets has been configured, not all formats may be available.

Note

You can use GetOptionInt to get the hotspot when loading cursor files:

hotspot_x = image.GetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_X)
hotspot_y = image.GetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_Y)


Loads an image from a file.

If no handler type is provided, the library will try to autodetect the format.

Parameters
Return type

bool

Loads an image from a file.

If no handler type is provided, the library will try to autodetect the format.

Parameters
• name (string) – Name of the file from which to load the image.

• mimetype (string) – MIME type string (for example ‘image/jpeg’)

• index (int) – See the description in the LoadFile overload.

Return type

bool

Loads an image from an input stream.

Parameters
• stream (wx.InputStream) – Opened input stream from which to load the image. Currently, the stream must support seeking.

• mimetype (string) – MIME type string (for example ‘image/jpeg’)

• index (int) – See the description in the LoadFile overload.

Return type

bool

Mirror(self, horizontally=True)

Returns a mirrored copy of the image.

The parameter horizontally indicates the orientation.

Parameters

horizontally (bool) –

Return type

wx.Image

Paste(self, image, x, y)

Copy the data of the given image to the specified position in this image.

Parameters
• image (wx.Image) –

• x (int) –

• y (int) –

static RGBtoHSV(rgb)

Converts a color in RGB color space to HSV color space.

Parameters

rgb (RGBValue) –

Return type

HSVValue

static RemoveHandler(name)

Finds the handler with the given name, and removes it.

The handler is also deleted.

Parameters

name (string) – The handler name.

Return type

bool

Returns

True if the handler was found and removed, False otherwise.

Replace(self, r1, g1, b1, r2, g2, b2)

Replaces the colour specified by r1,g1,b1 by the colour r2,g2,b2.

Parameters
• r1 (int) –

• g1 (int) –

• b1 (int) –

• r2 (int) –

• g2 (int) –

• b2 (int) –

Rescale(self, width, height, quality=IMAGE_QUALITY_NORMAL)

Changes the size of the image in-place by scaling it: after a call to this function,the image will have the given width and height.

For a description of the quality parameter, see the Scale function. Returns the (modified) image itself.

Parameters
Return type

wx.Image

Resize(self, size, pos, red=-1, green=-1, blue=-1)

Changes the size of the image in-place without scaling it by adding either a border with the given colour or cropping as necessary.

The image is pasted into a new image with the given size and background colour at the position pos relative to the upper left of the new image.

If red = green = blue = -1 then use either the current mask colour if set or find, use, and set a suitable mask colour for any newly exposed areas.

Parameters
• size (wx.Size) –

• pos (wx.Point) –

• red (int) –

• green (int) –

• blue (int) –

Return type

wx.Image

Returns

The (modified) image itself.

wx.Size

Rotate(self, angle, rotationCentre, interpolating=True, offsetAfterRotation=None)

Passing True to interpolating results in better image quality, but is slower.

If the image has a mask, then the mask colour is used for the uncovered pixels in the rotated image background. Else, black (rgb 0, 0, 0) will be used.

Returns the rotated image, leaving this image intact.

Parameters
• angle (float) –

• rotationCentre (wx.Point) –

• interpolating (bool) –

• offsetAfterRotation (wx.Point) –

Return type

wx.Image

Rotate180(self)

Returns a copy of the image rotated by 180 degrees.

Return type

wx.Image

New in version 2.9.2.

Rotate90(self, clockwise=True)

Returns a copy of the image rotated 90 degrees in the direction indicated by clockwise.

Parameters

clockwise (bool) –

Return type

wx.Image

RotateHue(self, angle)

Rotates the hue of each pixel in the image by angle, which is a float in the range of -1.0 to +1.0, where -1.0 corresponds to -360 degrees and +1.0 corresponds to +360 degrees.

Parameters

angle (float) –

SaveFile(self, *args, **kw)

SaveFile (self, stream, mimetype)

Saves an image in the given stream.

Parameters
• stream (wx.OutputStream) – Opened output stream to save the image to.

• mimetype (string) – MIME type.

Return type

bool

Returns

True if the operation succeeded, False otherwise.

Note

Depending on how wxWidgets has been configured, not all formats may be available.

Note

You can use SetOption to set the hotspot when saving an image into a cursor file (default hotspot is in the centre of the image):

image.SetOption(wx.IMAGE_OPTION_CUR_HOTSPOT_X, hotspotX)
image.SetOption(wx.IMAGE_OPTION_CUR_HOTSPOT_Y, hotspotY)


SaveFile (self, name, type)

Saves an image in the named file.

Parameters
• name (string) – Name of the file to save the image to.

• type (BitmapType) – Currently these types can be used:

• wx.BITMAP_TYPE_BMP: Save a BMP image file.

• wx.BITMAP_TYPE_JPEG: Save a JPEG image file.

• wx.BITMAP_TYPE_PNG: Save a PNG image file.

• wx.BITMAP_TYPE_PCX: Save a PCX image file (tries to save as 8-bit if possible, falls back to 24-bit otherwise).

• wx.BITMAP_TYPE_PNM: Save a PNM image file (as raw RGB always).

• wx.BITMAP_TYPE_TIFF: Save a TIFF image file.

• wx.BITMAP_TYPE_XPM: Save a XPM image file.

• wx.BITMAP_TYPE_ICO: Save a Windows icon file (ICO). The size may be up to 255 wide by 127 high. A single image is saved in 8 colors at the size supplied.

• wx.BITMAP_TYPE_CUR: Save a Windows cursor file (CUR).

Return type

bool

SaveFile (self, name, mimetype)

Saves an image in the named file.

Parameters
• name (string) – Name of the file to save the image to.

• mimetype (string) – MIME type.

Return type

bool

SaveFile (self, name)

Saves an image in the named file.

File type is determined from the extension of the file name. Note that this function may fail if the extension is not recognized! You can use one of the forms above to save images to files with non-standard extensions.

Parameters

name (string) – Name of the file to save the image to.

Return type

bool

SaveFile (self, stream, type)

Saves an image in the given stream.

Parameters
Return type

bool

Scale(self, width, height, quality=IMAGE_QUALITY_NORMAL)

Returns a scaled version of the image.

This is also useful for scaling bitmaps in general as the only other way to scale bitmaps is to blit a wx.MemoryDC into another wx.MemoryDC.

The parameter quality determines what method to use for resampling the image, see ImageResizeQuality documentation.

It should be noted that although using IMAGE_QUALITY_HIGH produces much nicer looking results it is a slower method. Downsampling will use the box averaging method which seems to operate very fast. If you are upsampling larger images using this method you will most likely notice that it is a bit slower and in extreme cases it will be quite substantially slower as the bicubic algorithm has to process a lot of data.

It should also be noted that the high quality scaling may not work as expected when using a single mask colour for transparency, as the scaling will blur the image and will therefore remove the mask partially. Using the alpha channel will work.

Example:

# get the bitmap from somewhere
bmp = wx.Bitmap('my_png.png', wx.BITMAP_TYPE_PNG)

# rescale it to have size of 32*32
if bmp.GetWidth() != 32 or bmp.GetHeight() != 32:

image = bmp.ConvertToImage()
bmp = wx.Bitmap(image.Scale(32, 32))

# another possibility:
image.Rescale(32, 32)
bmp = wx.Bitmap(image)

Parameters
Return type

wx.Image

SetAlpha(self, *args, **kw)

SetAlpha (self, x, y, alpha)

Sets the alpha value for the given pixel.

This function should only be called if the image has alpha channel data, use HasAlpha to check for this.

Parameters
• x (int) –

• y (int) –

• alpha (int) –

SetAlpha (self, alpha)

This function is similar to SetData and has similar restrictions.

The pointer passed to it may however be None in which case the function will allocate the alpha array internally

If the pointer is not None, it must have one byte for each image pixel and be allocated with malloc(). wx.Image takes ownership of the pointer and will free it unless static_data parameter is set to True

SetAlphaBuffer(self, alpha)

Sets the internal image alpha pointer to point at a Python buffer object. This can save making an extra copy of the data but you must ensure that the buffer object lives lives at least as long as the Image does.

SetData(self, *args, **kw)

SetData (self, data)

Sets the image data without performing checks.

The data given must have the size (widthheight3) or results will be unexpected. Don’t use this method if you aren’t sure you know what you are doing.

The data must have been allocated with malloc() , NOT with operator new.

If static_data is False, after this call the pointer to the data is owned by the wx.Image object, that will be responsible for deleting it. Do not pass to this function a pointer obtained through GetData .

SetData (self, data, new_width, new_height)

SetDataBuffer(self, *args, **kw)

Sets the internal image data pointer to point at a Python buffer object. This can save making an extra copy of the data but you must ensure that the buffer object lives lives at least as long as the Image does.

SetDataBuffer (self, data)

SetDataBuffer (self, data, new_width, new_height)

SetMask(self, hasMask=True)

Specifies whether there is a mask or not.

The area of the mask is determined by the current mask colour.

Parameters

SetMaskColour(self, red, green, blue)

Sets the mask colour for this image (and tells the image to use the mask).

Parameters
• red (int) –

• green (int) –

• blue (int) –

SetMaskFromImage(self, mask, mr, mg, mb)

Sets image’s mask so that the pixels that have RGB value of mr,mg,mb in mask will be masked in the image.

This is done by first finding an unused colour in the image, setting this colour as the mask colour and then using this colour to draw all pixels in the image who corresponding pixel in mask has given RGB value.

The parameter mask is the mask image to extract mask shape from. It must have the same dimensions as the image.

The parameters mr, mg, mb are the RGB values of the pixels in mask that will be used to create the mask.

Parameters

• mr (int) –

• mg (int) –

• mb (int) –

Return type

bool

Returns

Returns False if mask does not have same dimensions as the image or if there is no unused colour left. Returns True if the mask was successfully applied.

Note

Note that this method involves computing the histogram, which is a computationally intensive operation.

SetOption(self, *args, **kw)

SetOption (self, name, value)

Sets a user-defined option.

The function is case-insensitive to name.

For example, when saving as a JPEG file, the option quality is used, which is a number between 0 and 100 (0 is terrible, 100 is very good).

The lists of the currently supported options are in GetOption and GetOptionInt function docs.

Parameters
• name (string) –

• value (string) –

SetOption (self, name, value)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Parameters
• name (string) –

• value (int) –

SetPalette(self, palette)

Associates a palette with the image.

The palette may be used when converting wx.Image to wx.Bitmap (MSW only at present) or in file save operations (none as yet).

Parameters

palette (wx.Palette) –

SetRGB(self, *args, **kw)

SetRGB (self, x, y, r, g, b)

Set the color of the pixel at the given x and y coordinate.

Parameters
• x (int) –

• y (int) –

• r (int) –

• g (int) –

• b (int) –

SetRGB (self, rect, red, green, blue)

Sets the colour of the pixels within the given rectangle.

This routine performs bounds-checks for the coordinate so it can be considered a safe way to manipulate the data.

Parameters
• rect (wx.Rect) –

• red (int) –

• green (int) –

• blue (int) –

SetType(self, type)

Set the type of image returned by GetType .

This method is mostly used internally by the library but can also be called from the user code if the image was created from data in the given bitmap format without using LoadFile (which would set the type correctly automatically).

Notice that the image must be created before this function is called.

Parameters

type (BitmapType) – One of bitmap type constants, BITMAP_TYPE_INVALID is a valid value for it and can be used to reset the bitmap type to default but BITMAP_TYPE_MAX is not allowed here.

New in version 2.9.0.

Size(self, size, pos, red=-1, green=-1, blue=-1)

Returns a resized version of this image without scaling it by adding either a border with the given colour or cropping as necessary.

The image is pasted into a new image with the given size and background colour at the position pos relative to the upper left of the new image.

If red = green = blue = -1 then the areas of the larger image not covered by this image are made transparent by filling them with the image mask colour (which will be allocated automatically if it isn’t currently set).

Otherwise, the areas will be filled with the colour with the specified RGB components.

Parameters
• size (wx.Size) –

• pos (wx.Point) –

• red (int) –

• green (int) –

• blue (int) –

Return type

wx.Image

__bool__(self)
Return type

int

__nonzero__(self)
Return type

int

### Properties¶

Height

MaskBlue

MaskGreen

MaskRed

Type

Width