|  | Home · Overviews · Examples

# QImage Class Reference
[com.trolltech.qt.gui module]

The `QImage` class provides a hardware-independent image representation that allows direct access to the pixel data, and can be used as a paint device. More...

Inherits .

## Detailed Description

The `QImage` class provides a hardware-independent image representation that allows direct access to the pixel data, and can be used as a paint device.

Qt provides four classes for handling image data: `QImage`, `QPixmap`, `QBitmap` and `QPicture`. `QImage` is designed and optimized for I/O, and for direct pixel access and manipulation, while `QPixmap` is designed and optimized for showing images on screen. `QBitmap` is only a convenience class that inherits `QPixmap`, ensuring a depth of 1. Finally, the `QPicture` class is a paint device that records and replays `QPainter` commands.

Because `QImage` is a `QPaintDevice` subclass, `QPainter` can be used to draw directly onto images. When using `QPainter` on a `QImage`, the painting can be performed in another thread than the current GUI thread, that is except rendering text (because `QFont` is GUI dependent). To render text in another thread, the text must first be derived as a `QPainterPath` in the GUI thread.

The `QImage` class supports several image formats described by the Format enum. These include monochrome, 8-bit, 32-bit and alpha-blended images which are available in all versions of Qt 4.x. In addition, `QImage` supports several formats that are specific to Qtopia Core.

`QImage` provides a collection of functions that can be used to obtain a variety of information about the image. There are also several functions that enables transformation of the image.

`QImage` objects can be passed around by value since the `QImage` class uses implicit data sharing. `QImage` objects can also be streamed and compared.

- Reading and Writing Image Files
- Image Information
- Pixel Manipulation
- Image Formats
- Image Transformations
- Legal Information

### Reading and Writing Image Files

`QImage` provides several ways of loading an image file: The file can be loaded when constructing the `QImage` object, or by using the load() or loadFromData() functions later on. `QImage` also provides the static fromData() function, constructing a `QImage` from the given data. When loading an image, the file name can either refer to an actual file on disk or to one of the application's embedded resources. See The Qt Resource System overview for details on how to embed images and other resource files in the application's executable.

Simply call the save() function to save a `QImage` object.

The complete list of supported file formats are available through the QImageReader::supportedImageFormats() and QImageWriter::supportedImageFormats() functions. New file formats can be added as plugins. By default, Qt supports the following formats:

Format | Description | Qt's support
--- | --- | ---
BMP | Windows Bitmap | Read/write
GIF | Graphic Interchange Format (optional) | Read
JPG | Joint Photographic Experts Group | Read/write
JPEG | Joint Photographic Experts Group | Read/write
PNG | Portable Network Graphics | Read/write
PBM | Portable Bitmap | Read
PGM | Portable Graymap | Read
PPM | Portable Pixmap | Read/write
TIFF | Tagged Image File Format | Read/write
XBM | X11 Bitmap | Read/write
XPM | X11 Pixmap | Read/write

(To configure Qt with GIF support, pass `-qt-gif` to the `configure` script or check the appropriate option in the graphical installer.)

### Image Information

`QImage` provides a collection of functions that can be used to obtain a variety of information about the image:

| Available Functions
--- | ---
Geometry | The `size`, `width`, `height`, `dotsPerMeterX`, and `dotsPerMeterY` functions provide information about the image size and aspect ratio. The `rect` function returns the image's enclosing rectangle. The `valid` function tells if a given pair of coordinates is within this rectangle. The `offset` function returns the number of pixels by which the image is intended to be offset by when positioned relative to other images, which also can be manipulated using the `setOffset` function.
Colors | The color of a pixel can be retrieved by passing its coordinates to the `pixel` function. The `pixel` function returns the color as a QRgb value indepedent of the image's format. In case of monochrome and 8-bit images, the `numColors` and `colorTable` functions provide information about the color components used to store the image data: The `colorTable` function returns the image's entire color table. To obtain a single entry, use the `pixelIndex` function to retrieve the pixel index for a given pair of coordinates, then use the `color` function to retrieve the color. Note that if you create an 8-bit image manually, you have to set a valid color table on the image as well. The `hasAlphaChannel` function tells if the image's format respects the alpha channel, or not. The `allGray` and `isGrayscale` functions tell whether an image's colors are all shades of gray. See also the Pixel Manipulation and Image Transformations sections.
Text | The `text` function returns the image text associated with the given text key. An image's text keys can be retrieved using the `textKeys` function. Use the `setText` function to alter an image's text.
Low-level information | The `depth` function returns the depth of the image. The supported depths are 1 (monochrome), 8 and 32 (for more information see the Image Formats section). The `format`, `bytesPerLine`, and `numBytes` functions provide low-level information about the data stored in the image. The `cacheKey` function returns a number that uniquely identifies the contents of this `QImage` object.

### Pixel Manipulation

The functions used to manipulate an image's pixels depend on the image format. The reason is that monochrome and 8-bit images are index-based and use a color lookup table, while 32-bit images store ARGB values directly. For more information on image formats, see the Image Formats section.

In case of a 32-bit image, the `setPixel` function can be used to alter the color of the pixel at the given coordinates to any other color specified as an ARGB quadruplet. To make a suitable QRgb value, use the qRgb() (adding a default alpha component to the given RGB values, i.e. creating an opaque color) or qRgba() function. For example:

        QImage image(3, 3, QImage::Format_RGB32);
        QRgb value;

        value = qRgb(189, 149, 39); // 0xffbd9527
        image.setPixel(1, 1, value);

        value = qRgb(122, 163, 39); // 0xff7aa327
        image.setPixel(0, 1, value);
        image.setPixel(1, 0, value);

        value = qRgb(237, 187, 51); // 0xffedba31
        image.setPixel(2, 1, value);
32-bit

In case of a 8-bit and monchrome images , the pixel value is only an index from the image's color table. So the `setPixel` function can only be used to alter the color of the pixel at the given coordinates to a predefined color from the image's color table, i.e. it can only change the pixel's index value. To alter or add a color to an image's color table, use the `setColor` function.

An entry in the color table is an ARGB quadruplet encoded as an QRgb value. Use the qRgb() and qRgba() functions to make a suitable QRgb value for use with the `setColor` function. For example:

        QImage image(3, 3, QImage::Format_Indexed8);
        QRgb value;

        value = qRgb(122, 163, 39); // 0xff7aa327
        image.setColor(0, value);

        value = qRgb(237, 187, 51); // 0xffedba31
        image.setColor(1, value);

        value = qRgb(189, 149, 39); // 0xffbd9527
        image.setColor(2, value);

        image.setPixel(0, 1, 0);
        image.setPixel(1, 0, 0);
        image.setPixel(1, 1, 2);
        image.setPixel(2, 1, 1);
8-bit

`QImage` also provide the `scanLine` function which returns a pointer to the pixel data at the scanline with the given index, and the `bits` function which returns a pointer to the first pixel data (this is equivalent to `scanLine(0)`).

### Image Formats

Each pixel stored in a `QImage` is represented by an integer. The size of the integer varies depending on the format. `QImage` supports several image formats described by the Format enum. The monochrome (1-bit), 8-bit and 32-bit images are available in all versions of Qt. In addition Qtopia Core also supports 2-bit, 4-bit, and 16-bit images. For more information about the Qtopia specific formats, see the documentation of the Format enum.

Monochrome images are stored using 1-bit indexes into a color table with at most two colors. There are two different types of monochrome images: big endian (MSB first) or little endian (LSB first) bit order.

8-bit images are stored using 8-bit indexes into a color table, i.e. they have a single byte per pixel. The color table is a QVector<QRgb>, and the QRgb typedef is equivalent to an unsigned int containing an ARGB quadruplet on the format 0xAARRGGBB.

32-bit images have no color table; instead, each pixel contains an QRgb value. There are three different types of 32-bit images storing RGB (i.e. 0xffRRGGBB), ARGB and premultiplied ARGB values respectively. In the premultiplied format the red, green, and blue channels are multiplied by the alpha component divided by 255.

An image's format can be retrieved using the `format` function. Use the `convertToFormat` functions to convert an image into another format. The `allGray` and `isGrayscale` functions tell whether a color image can safely be converted to a grayscale image.

### Image Transformations

`QImage` supports a number of functions for creating a new image that is a transformed version of the original: The `createAlphaMask` function builds and returns a 1-bpp mask from the alpha buffer in this image, and the `createHeuristicMask` function creates and returns a 1-bpp heuristic mask for this image. The latter function works by selecting a color from one of the corners, then chipping away pixels of that color starting at all the edges.

The `mirrored` function returns a mirror of the image in the desired direction, the `scaled` returns a copy of the image scaled to a rectangle of the desired measures, the `rgbSwapped` function constructs a BGR image from a RGB image, and the `alphaChannel` function constructs an image from this image's alpha channel.

The `scaledToWidth` and `scaledToHeight` functions return scaled copies of the image.

The `transformed` function returns a copy of the image that is transformed with the given transformation matrix and transformation mode: Internally, the transformation matrix is adjusted to compensate for unwanted translation, i.e. `transformed` returns the smallest image containing all transformed points of the original image. The static `trueMatrix` function returns the actual matrix used for transforming the image.

There are also functions for changing attributes of an image in-place:

Function | Description
--- | ---
`setAlphaChannel` | Sets the alpha channel of the image.
`setDotsPerMeterX` | Defines the aspect ratio by setting the number of pixels that fit horizontally in a physical meter.
`setDotsPerMeterY` | Defines the aspect ratio by setting the number of pixels that fit vertically in a physical meter.
`fill` | Fills the entire image with the given pixel value.
`invertPixels` | Inverts all pixel values in the image using the given `InvertMode` value.
`setColorTable` | Sets the color table used to translate color indexes. Only monochrome and 8-bit formats.
`setNumColors` | Resizes the color table. Only monochrome and 8-bit formats.

### Legal Information

For smooth scaling, the `transformed` functions use code based on smooth scaling algorithm by Daniel M. Duley.

Copyright (C) 2004, 2005 Daniel M. Duley

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

See also `QImageReader`, `QImageWriter`, `QPixmap`, `QSvgRenderer`, Image Composition Example, Image Viewer Example, Scribble Example, and Pixelator Example.