Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

QImage Class Reference
[QtGui 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...

 #include <QImage>

Inherits QPaintDevice.

Public Types

Public Functions

Static Public Members

Related Non-Members

Additional Inherited Members


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

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:

FormatDescriptionQt's support
BMPWindows BitmapRead/write
GIFGraphic Interchange Format (optional)Read
JPGJoint Photographic Experts GroupRead/write
JPEGJoint Photographic Experts GroupRead/write
PNGPortable Network GraphicsRead/write
PBMPortable BitmapRead
PGMPortable GraymapRead
PPMPortable PixmapRead/write
XBMX11 BitmapRead/write
XPMX11 PixmapRead/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
GeometryThe 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.

ColorsThe 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.

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.

TextThe 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 informationThe 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 serialNumber() 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:

FunctionDescription
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.

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


Member Type Documentation

enum QImage::Format

The following image formats are available in all versions of Qt:

ConstantValueDescription
QImage::Format_Invalid0The image is invalid.
QImage::Format_Mono1The image is stored using 1-bit per pixel. Bytes are packed with the most significant bit (MSB) first.
QImage::Format_MonoLSB2The image is stored using 1-bit per pixel. Bytes are packed with the less significant bit (LSB) first.
QImage::Format_Indexed83The image is stored using 8-bit indexes into a colormap.
QImage::Format_RGB324The image is stored using a 32-bit RGB format (0xffRRGGBB).
QImage::Format_ARGB325The image is stored using a 32-bit ARGB format (0xAARRGGBB).
QImage::Format_ARGB32_Premultiplied6The image is stored using a premultiplied 32-bit ARGB format (0xAARRGGBB), i.e. the red, green, and blue channels are multiplied by the alpha component divided by 255. (If RR, GG, or BB has a higher value than the alpha channel, the results are undefined.) Certain operations (such as image composition using alpha blending) are faster using premultiplied ARGB32 than with plain ARGB32.

The following image format is specific to Qtopia Core:

ConstantValueDescription
QImage::Format_RGB167The image is stored using a 16-bit RGB format (5-6-5).

See also format() and convertToFormat().

enum QImage::InvertMode

This enum type is used to describe how pixel values should be inverted in the invertPixels() function.

ConstantValueDescription
QImage::InvertRgb0Invert only the RGB values and leave the alpha channel unchanged.
QImage::InvertRgba1Invert all channels, including the alpha channel.

See also invertPixels().


Member Function Documentation

QImage::QImage ()

Constructs a null image.

See also isNull().

QImage::QImage ( const QSize & size, Format format )

Constructs an image with the given size and format.

QImage::QImage ( int width, int height, Format format )

Constructs an image with the given width, height and format.

QImage::QImage ( uchar * data, int width, int height, Format format )

Constructs an image with the given width, height and format, that uses an existing memory buffer, data. The width and height must be specified in pixels, data must be 32-bit aligned, and each scanline of data in the image must also be 32-bit aligned.

The buffer must remain valid throughout the life of the QImage. The image does not delete the buffer at destruction.

If the image is in an indexed color format, set the color table for the image using setColorTable().

QImage::QImage ( const uchar * data, int width, int height, Format format )

Constructs an image with the given width, height and format, that uses an existing read-only memory buffer, data. The width and height must be specified in pixels, data must be 32-bit aligned, and each scanline of data in the image must also be 32-bit aligned.

The buffer must remain valid throughout the life of the QImage and all copies that have not been modified or otherwise detached from the original buffer. The image does not delete the buffer at destruction.

If the image is in an indexed color format, set the color table for the image using setColorTable().

Unlike the similar QImage constructor that takes a non-const data buffer, this version will never alter the contents of the buffer. For example, calling QImage::bits() will return a deep copy of the image, rather than the buffer passed to the constructor. This allows for the efficiency of constructing a QImage from raw data, without the possibility of the raw data being changed.

QImage::QImage ( const char * const[] xpm )

Constructs an image from the given xpm image.

Make sure that the image is a valid XPM image. Errors are silently ignored.

Note that it's possible to squeeze the XPM variable a little bit by using an unusual declaration:

 static const char * const start_xpm[] = {
     "16 15 8 1",
     "a c #cec6bd",
 ....

The extra const makes the entire definition read-only, which is slightly more efficient (e.g. when the code is in a shared library) and ROMable when the application is to be stored in ROM.

QImage::QImage ( const QString & fileName, const char * format = 0 )

Constructs an image and tries to load the image from the file with the given fileName.

The loader attempts to read the image using the specified format. If the format is not specified (which is the default), the loader probes the file for a header to guess the file format.

If the loading of the image failed, this object is a null image.

The file name can either refer to an actual file on disk or to one of the application's embedded resources. See the Resource System overview for details on how to embed images and other resource files in the application's executable.

See also isNull() and Reading and Writing Image Files.

QImage::QImage ( const char * fileName, const char * format = 0 )

Constructs an image and tries to load the image from the file with the given fileName.

The loader attempts to read the image using the specified format. If the format is not specified (which is the default), the loader probes the file for a header to guess the file format.

If the loading of the image failed, this object is a null image.

The file name can either refer to an actual file on disk or to one of the application's embedded resources. See the Resource System overview for details on how to embed images and other resource files in the application's executable.

You can disable this constructor by defining QT_NO_CAST_FROM_ASCII when you compile your applications. This can be useful, for example, if you want to ensure that all user-visible strings go through QObject::tr().

See also QString::fromAscii(), isNull(), and Reading and Writing Image Files.

QImage::QImage ( const QImage & image )

Constructs a shallow copy of the given image.

For more information about shallow copies, see the Implicit Data Sharing documentation.

See also copy().

QImage::~QImage ()

Destroys the image and cleans up.

bool QImage::allGray () const

Returns true if all the colors in the image are shades of gray (i.e. their red, green and blue components are equal); otherwise false.

Note that this function is slow for images without color table.

See also isGrayscale().

QImage QImage::alphaChannel () const

Returns the alpha channel of the image as a new grayscale QPixmap in which each pixel's red, green, and blue values are given the alpha value of the original image. The color depth of the returned image is 8-bit.

You can see an example of use of this function in QPixmap's alphaChannel(), which works in the same way as this function on QPixmaps.

See also setAlphaChannel() and Pixmap sa setAlphaChannel(), hasAlphaChannel(), {QImage#Image Transformations}{Image Transformations}.

uchar * QImage::bits ()

Returns a pointer to the first pixel data. This is equivalent to scanLine(0).

See also scanLine() and numBytes().

const uchar * QImage::bits () const

This is an overloaded member function, provided for convenience.

int QImage::bytesPerLine () const

Returns the number of bytes per image scanline.

This is equivalent to numBytes()/ height().

See also scanLine().

QRgb QImage::color ( int i ) const

Returns the color in the color table at index i. The first color is at index 0.

The colors in an image's color table are specified as ARGB quadruplets (QRgb). Use the qAlpha(), qRed(), qGreen(), and qBlue() functions to get the color value components.

See also setColor(), pixelIndex(), and Pixel Manipulation.

QVector<QRgb> QImage::colorTable () const

Returns a list of the colors contained in the image's color table, or an empty list if the image does not have a color table

See also setColorTable(), numColors(), and color().

QImage QImage::convertToFormat ( Format format, Qt::ImageConversionFlags flags = Qt::AutoColor ) const

Returns a copy of the image in the given format.

The specified image conversion flags control how the image data is handled during the conversion process.

See also Image Format.

QImage QImage::convertToFormat ( Format format, const QVector<QRgb> & colorTable, Qt::ImageConversionFlags flags = Qt::AutoColor ) const

This is an overloaded member function, provided for convenience.

Returns a copy of the image converted to the given format, using the specified colorTable.

Conversion from 32 bit to 8 bit indexed is a slow operation and will use a straightforward nearest color approach, with no dithering.

QImage QImage::copy ( const QRect & rectangle = QRect() ) const

Returns a sub-area of the image as a new image.

The returned image is copied from the position (rectangle.x(), rectangle.y()) in this image, and will always have the size of the given rectangle.

In areas beyond this image, pixels are set to 0. For 32-bit RGB images, this means black; for 32-bit ARGB images, this means transparent black; for 8-bit images, this means the color with index 0 in the color table which can be anything; for 1-bit images, this means Qt::color0.

If the given rectangle is a null rectangle the entire image is copied.

See also QImage().

QImage QImage::copy ( int x, int y, int width, int height ) const

This is an overloaded member function, provided for convenience.

The returned image is copied from the position (x, y) in this image, and will always have the given width and height. In areas beyond this image, pixels are set to 0.

QImage QImage::createAlphaMask ( Qt::ImageConversionFlags flags = Qt::AutoColor ) const

Builds and returns a 1-bpp mask from the alpha buffer in this image. Returns a null image if the image's format is QImage::Format_RGB32.

The flags argument is a bitwise-OR of the Qt::ImageConversionFlags, and controls the conversion process. Passing 0 for flags sets all the default options.

The returned image has little-endian bit order (i.e. the image's format is QImage::Format_MonoLSB), which you can convert to big-endian (QImage::Format_Mono) using the convertToFormat() function.

See also createHeuristicMask() and Image Transformations.

QImage QImage::createHeuristicMask ( bool clipTight = true ) const

Creates and returns a 1-bpp heuristic mask for this image.

The function works by selecting a color from one of the corners, then chipping away pixels of that color starting at all the edges. The four corners vote for which color is to be masked away. In case of a draw (this generally means that this function is not applicable to the image), the result is arbitrary.

The returned image has little-endian bit order (i.e. the image's format is QImage::Format_MonoLSB), which you can convert to big-endian (QImage::Format_Mono) using the convertToFormat() function.

If clipTight is true (the default) the mask is just large enough to cover the pixels; otherwise, the mask is larger than the data pixels.

Note that this function disregards the alpha buffer.

See also createAlphaMask() and Image Transformations.

int QImage::depth () const

Returns the depth of the image.

The image depth is the number of bits used to encode a single pixel, also called bits per pixel (bpp) or bit planes of an image.

The supported depths are 1, 8 and 32.

See also convertToFormat(), Image Formats, and Image Information.

int QImage::dotsPerMeterX () const

Returns the number of pixels that fit horizontally in a physical meter. Together with dotsPerMeterY(), this number defines the intended scale and aspect ratio of the image.

See also setDotsPerMeterX() and Image Information.

int QImage::dotsPerMeterY () const

Returns the number of pixels that fit vertically in a physical meter. Together with dotsPerMeterX(), this number defines the intended scale and aspect ratio of the image.

See also setDotsPerMeterY() and Image Information.

void QImage::fill ( uint pixelValue )

Fills the entire image with the given pixelValue.

If the depth of this image is 1, only the lowest bit is used. If you say fill(0), fill(2), etc., the image is filled with 0s. If you say fill(1), fill(3), etc., the image is filled with 1s. If the depth is 8, the lowest 8 bits are used and if the depth is 16 the lowest 16 bits are used.

Note: QImage::pixel() returns the color of the pixel at the given coordinates while QColor::pixel() returns the pixel value of the underlying window system (essentially an index value), so normally you will want to use QImage::pixel() to use a color from an existing image or QColor::rgb() to use a specific color.

See also depth() and Image Transformations.

Format QImage::format () const

Returns the format of the image.

See also Image Formats.

QImage QImage::fromData ( const uchar * data, int size, const char * format = 0 )   [static]

Constructs a QImage from the first size bytes of the given binary data. the loader attempts to read the image using the specified format. If the format is not specified (which is the default), the loader probes the file for a header to guess the file format.

If the loading of the image failed, this object is a null image.

See also load(), save(), and Reading and Writing Image Files.

QImage QImage::fromData ( const QByteArray & data, const char * format = 0 )   [static]

This is an overloaded member function, provided for convenience.

Loads an image from the given QByteArray data.

bool QImage::hasAlphaChannel () const

Returns true if the image has a format that respects the alpha channel, otherwise returns false.

See also alphaChannel() and Image Information.

int QImage::height () const

Returns the height of the image.

See also Image Information.

void QImage::invertPixels ( InvertMode mode = InvertRgb )

Inverts all pixel values in the image.

The given invert mode only have a meaning when the image's depth is 32. The default mode is InvertRgb, which leaves the alpha channel unchanged. If the mode is InvertRgba, the alpha bits are also inverted.

Inverting an 8-bit image means to replace all pixels using color index i with a pixel using color index 255 minus i. The same is the case for a 1-bit image. Note that the color table is not changed.

See also Image Transformations.

bool QImage::isGrayscale () const

For 32-bit images, this function is equivalent to allGray().

For 8-bpp images, this function returns true if color(i) is QRgb(i, i, i) for all indexes of the color table; otherwise returns false.

See also allGray() and Image Formats.

bool QImage::isNull () const

Returns true if it is a null image, otherwise returns false.

A null image has all parameters set to zero and no allocated data.

bool QImage::load ( const QString & fileName, const char * format = 0 )

Loads an image from the file with the given fileName. Returns true if the image was successfully loaded; otherwise returns false.

The loader attempts to read the image using the specified format. If the format is not specified (which is the default), the loader probes the file for a header to guess the file format.

The file name can either refer to an actual file on disk or to one of the application's embedded resources. See the Resource System overview for details on how to embed images and other resource files in the application's executable.

See also Reading and Writing Image Files.

bool QImage::load ( QIODevice * device, const char * format )

This is an overloaded member function, provided for convenience.

This function reads a QImage from the given device. This can, for example, be used to load an image directly into a QByteArray.

bool QImage::loadFromData ( const uchar * data, int len, const char * format = 0 )

Loads an image from the first len bytes of the given binary data. Returns true if the image was successfully loaded; otherwise returns false.

The loader attempts to read the image using the specified format. If the format is not specified (which is the default), the loader probes the file for a header to guess the file format.

See also Reading and Writing Image Files.

bool QImage::loadFromData ( const QByteArray & data, const char * format = 0 )

This is an overloaded member function, provided for convenience.

Loads an image from the given QByteArray data.

QImage QImage::mirrored ( bool horizontal = false, bool vertical = true ) const

Returns a mirror of the image, mirrored in the horizontal and/or the vertical direction depending on whether horizontal and vertical are set to true or false.

Note that the original image is not changed.

See also Image Transformations.

int QImage::numBytes () const

Returns the number of bytes occupied by the image data.

See also bytesPerLine(), bits(), and Image Information.

int QImage::numColors () const

Returns the size of the color table for the image.

Notice that numColors() returns 0 for 32-bpp images because these images do not use color tables, but instead encode pixel values as ARGB quadruplets.

See also setNumColors() and Image Information.

QPoint QImage::offset () const

Returns the number of pixels by which the image is intended to be offset by when positioning relative to other images.

See also setOffset() and Image Information.

QRgb QImage::pixel ( const QPoint & position ) const

Returns the color of the pixel at the given position.

If the position is not valid, the results are undefined.

See also setPixel(), valid(), and Pixel Manipulation.

QRgb QImage::pixel ( int x, int y ) const

This is an overloaded member function, provided for convenience.

Returns the color of the pixel at coordinates (x, y).

int QImage::pixelIndex ( const QPoint & position ) const

Returns the pixel index at the given position.

If position is not valid, or if the image is not a paletted image (depth() > 8), the results are undefined.

See also valid(), depth(), and Pixel Manipulation.

int QImage::pixelIndex ( int x, int y ) const

This is an overloaded member function, provided for convenience.

Returns the pixel index at (x, y).

QRect QImage::rect () const

Returns the enclosing rectangle (0, 0, width(), height()) of the image.

See also Image Information.

QImage QImage::rgbSwapped () const

Returns a QImage in which the values of the red and blue components of all pixels have been swapped, effectively converting an RGB image to an BGR image.

The original QImage is not changed.

See also Image Transformations.

bool QImage::save ( const QString & fileName, const char * format = 0, int quality = -1 ) const

Saves the image to the file with the given fileName, using the given image file format and quality factor. If format is 0, QImage will attempt to guess the format by looking at fileName's suffix.

The quality factor must be in the range 0 to 100 or -1. Specify 0 to obtain small compressed files, 100 for large uncompressed files, and -1 (the default) to use the default settings.

Returns true if the image was successfully saved; otherwise returns false.

See also Reading and Writing Image Files.

bool QImage::save ( QIODevice * device, const char * format = 0, int quality = -1 ) const

This is an overloaded member function, provided for convenience.

This function writes a QImage to the given device.

This can, for example, be used to save an image directly into a QByteArray:

         QImage image;
         QByteArray ba;
         QBuffer buffer(&ba);
         buffer.open(QIODevice::WriteOnly);
         image.save(&buffer, "PNG"); // writes image into ba in PNG format

QImage QImage::scaled ( const QSize & size, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio, Qt::TransformationMode transformMode = Qt::FastTransformation ) const

Returns a copy of the image scaled to a rectangle defined by the given size according to the given aspectRatioMode and transformMode.

If the given size is empty, this function returns a null image.

See also isNull() and Image Transformations.

QImage QImage::scaled ( int width, int height, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio, Qt::TransformationMode transformMode = Qt::FastTransformation ) const

This is an overloaded member function, provided for convenience.

Returns a copy of the image scaled to a rectangle with the given width and height according to the given aspectRatioMode and transformMode.

If either the width or the height is zero or negative, this function returns a null image.

QImage QImage::scaledToHeight ( int height, Qt::TransformationMode mode = Qt::FastTransformation ) const

Returns a scaled copy of the image. The returned image is scaled to the given height using the specified transformation mode.

This function automatically calculates the width of the image so that the ratio of the image is preserved.

If the given height is 0 or negative, a null image is returned.

See also Image Transformations.

QImage QImage::scaledToWidth ( int width, Qt::TransformationMode mode = Qt::FastTransformation ) const

Returns a scaled copy of the image. The returned image is scaled to the given width using the specified transformation mode.

This function automatically calculates the height of the image so that its aspect ratio is preserved.

If the given width is 0 or negative, a null image is returned.

See also Image Transformations.

uchar * QImage::scanLine ( int i )

Returns a pointer to the pixel data at the scanline with index i. The first scanline is at index 0.

The scanline data is aligned on a 32-bit boundary.

Warning: If you are accessing 32-bpp image data, cast the returned pointer to QRgb* (QRgb has a 32-bit size) and use it to read/write the pixel value. You cannot use the uchar* pointer directly, because the pixel format depends on the byte order on the underlying platform. Use qRed(), qGreen(), qBlue(), and qAlpha() to access the pixels.

See also bytesPerLine(), bits(), and Pixel Manipulation.

const uchar * QImage::scanLine ( int i ) const

This is an overloaded member function, provided for convenience.

int QImage::serialNumber () const

Returns a number that identifies the contents of this QImage object. Distinct QImage objects can only have the same serial number if they refer to the same contents (but they don't have to).

Warning: The serial number doesn't necessarily change when the image is altered. This means that it may be dangerous to use it as a cache key.

See also operator==().

void QImage::setAlphaChannel ( const QImage & alphaChannel )

Sets the alpha channel of this image to the given alphaChannel.

If alphaChannel is an 8 bit grayscale image, the intensity values are written into this buffer directly. Otherwise, alphaChannel is converted to 32 bit and the intensity of the RGB pixel values is used.

Note that the image will be converted to the Format_ARGB32_Premultiplied format if the function succeeds.

See also alphaChannel(), Image Transformations, and Image Formats.

void QImage::setColor ( int index, QRgb colorValue )

Sets the color at the given index in the color table, to the given to colorValue.

The color value is an ARGB quadruplet.

See also color(), setColorTable(), and Pixel Manipulation.

void QImage::setColorTable ( const QVector<QRgb> colors )

Sets the color table used to translate color indexes to QRgb values, to the specified colors.

See also colorTable(), setColor(), and Image Transformations.

void QImage::setDotsPerMeterX ( int x )

Sets the number of pixels that fit horizontally in a physical meter, to x.

Together with dotsPerMeterY(), this number defines the intended scale and aspect ratio of the image.

See also dotsPerMeterX() and Image Information.

void QImage::setDotsPerMeterY ( int y )

Sets the number of pixels that fit vertically in a physical meter, to y.

Together with dotsPerMeterX(), this number defines the intended scale and aspect ratio of the image.

See also dotsPerMeterY() and Image Information.

void QImage::setNumColors ( int numColors )

Resizes the color table to contain numColors entries.

If the color table is expanded, all the extra colors will be set to transparent (i.e qRgba(0, 0, 0, 0)).

See also numColors(), colorTable(), and Image Transformations.

void QImage::setOffset ( const QPoint & offset )

Sets the the number of pixels by which the image is intended to be offset by when positioning relative to other images, to offset.

See also offset() and Image Information.

void QImage::setPixel ( const QPoint & position, uint index_or_rgb )

Sets the pixel index or color at the given position to index_or_rgb.

If the image's format is either monochrome or 8-bit, the given index_or_rgb value must be an index in the image's color table, otherwise the parameter must be a QRgb value.

If position is not a valid coordinate pair in the image, or if index_or_rgb >= numColors() in the case of monochrome and 8-bit images, the result is undefined.

See also pixel() and Pixel Manipulation.

void QImage::setPixel ( int x, int y, uint index_or_rgb )

This is an overloaded member function, provided for convenience.

Sets the pixel index or color at (x, y) to index_or_rgb.

void QImage::setText ( const QString & key, const QString & text )

Sets the image text to the given text and associate it with the given key.

If you just want to store a single text block (i.e., a "comment" or just a description), you can either pass an empty key, or use a generic key like "Description".

The image text is embedded into the image data when you call save() or QImageWriter::write().

Not all image formats support embedded text. You can find out if a specific image or format supports embedding text by using QImageWriter::supportsOption(). We give an example:

         QImageWriter writer;
         writer.setFormat("png");
         if (writer.supportsOption(QImageIOHandler::Description))
             qDebug() << "Png supports embedded text";

You can use QImageWriter::supportedImageFormats() to find out which image formats are available to you.

See also text() and textKeys().

QSize QImage::size () const

Returns the size of the image, i.e. its width() and height().

See also Image Information.

QString QImage::text ( const QString & key = QString() ) const

Returns the image text associated with the given key. If the specified key is an empty string, the whole image text is returned, with each key-text pair separated by a newline.

See also setText() and textKeys().

QStringList QImage::textKeys () const

Returns the text keys for this image.

You can use these keys with text() to list the image text for a certain key.

See also text().

QImage QImage::transformed ( const QMatrix & matrix, Qt::TransformationMode mode = Qt::FastTransformation ) const

Returns a copy of the image that is transformed using the given transformation matrix and transformation mode.

The transformation matrix is internally adjusted to compensate for unwanted translation; i.e. the image produced is the smallest image that contains all the transformed points of the original image. Use the trueMatrix() function to retrieve the actual matrix used for transforming an image

For smooth scaling down, this function uses code based on pnmscale.c by Jef Poskanzer.

pnmscale.c - read a portable anymap and scale it

Copyright (C) 1989, 1991 by Jef Poskanzer.

Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. This software is provided "as is" without express or implied warranty.

See also trueMatrix() and Image Transformations.

QMatrix QImage::trueMatrix ( const QMatrix & matrix, int width, int height )   [static]

Returns the actual matrix used for transforming an image with the given width, height and matrix.

When transforming an image using the transformed() function, the transformation matrix is internally adjusted to compensate for unwanted translation, i.e. transformed() returns the smallest image containing all transformed points of the original image. This function returns the modified matrix, which maps points correctly from the original image into the new image.

See also transformed() and Image Transformations.

bool QImage::valid ( const QPoint & pos ) const

Returns true if pos is a valid coordinate pair within the image; otherwise returns false.

See also rect() and QRect::contains().

bool QImage::valid ( int x, int y ) const

This is an overloaded member function, provided for convenience.

Returns true if QPoint(x, y) is a valid coordinate pair within the image; otherwise returns false.

int QImage::width () const

Returns the width of the image.

See also Image Information.

QImage::operator QVariant () const

Returns the image as a QVariant.

bool QImage::operator!= ( const QImage & image ) const

Returns true if this image and the given image have different contents; otherwise returns false.

The comparison can be slow, unless there is some obvious difference, such as different widths, in which case the function will return quickly.

See also operator=().

QImage & QImage::operator= ( const QImage & image )

Assigns a shallow copy of the given image to this image and returns a reference to this image.

For more information about shallow copies, see the Implicit Data Sharing documentation.

See also copy() and QImage().

bool QImage::operator== ( const QImage & image ) const

Returns true if this image and the given image have the same contents; otherwise returns false.

The comparison can be slow, unless there is some obvious difference (e.g. different size or format), in which case the function will return quickly.

See also operator=().


Related Non-Members

QDataStream & operator<< ( QDataStream & stream, const QImage & image )

This is an overloaded member function, provided for convenience.

Writes the given image to the given stream as a PNG image, or as a BMP image if the stream's version is 1. Note that writing the stream to a file will not produce a valid image file.

See also QImage::save() and Format of the QDataStream Operators.

QDataStream & operator>> ( QDataStream & stream, QImage & image )

This is an overloaded member function, provided for convenience.

Reads an image from the given stream and stores it in the given image.

See also QImage::load() and Format of the QDataStream Operators.


Member Type Documentation

enum QImage::Endian

This enum type is used to describe the endianness of the CPU and graphics hardware. It is provided here for compatibility with earlier versions of Qt.

Use the Format enum instead. The Format enum specify the endianess for monchrome formats, but for other formats the endianess is not relevant.

ConstantValueDescription
QImage::IgnoreEndian2Endianness does not matter. Useful for some operations that are independent of endianness.
QImage::BigEndian0Most significant bit first or network byte order, as on SPARC, PowerPC, and Motorola CPUs.
QImage::LittleEndian1Least significant bit first or little endian byte order, as on Intel x86.


Member Function Documentation

QImage::QImage ( int width, int height, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )

Constructs an image with the given width, height, depth, numColors colors and bitOrder.

Use the constructor that accepts a width, a height and a format (i.e. specifying the depth and bit order), in combination with the setNumColors() function, instead.

For example, if you have code like

 QImage image(width, height, depth, numColors);

you can rewrite it as

 QImage image(width, height, format);

 // For 8 bit images the default number of colors is 256. If
 // another number of colors is required it can be specified
 // using the setNumColors() function.
 image.setNumColors(numColors);

QImage::QImage ( const QSize & size, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )

Constructs an image with the given size, depth, numColors and bitOrder.

Use the constructor that accepts a size and a format (i.e. specifying the depth and bit order), in combination with the setNumColors() function, instead.

For example, if you have code like

 QSize mySize(width, height);
 QImage image(mySize, depth, numColors);

you can rewrite it as

 QSize mySize(width, height);
 QImage image(mySize, format);

 // For 8 bit images the default number of colors is 256. If
 // another number of colors is required it can be specified
 // using the setNumColors() function.
 image.setNumColors(numColors);

QImage::QImage ( uchar * data, int width, int height, int depth, const QRgb * colortable, int numColors, Endian bitOrder )

Constructs an image with the given width, height, depth, colortable, numColors and bitOrder, that uses an existing memory buffer, data.

Use the constructor that accepts a uchar pointer, a width, a height and a format (i.e. specifying the depth and bit order), in combination with the setColorTable() function, instead.

For example, if you have code like

 uchar *myData;
 QRgb *myColorTable;

 QImage image(myData, width, height, depth,
                        myColorTable, numColors, IgnoreEndian);

you can rewrite it as

 uchar *myData;
 QVector<QRgb> myColorTable;

 QImage image(myData, width, height, format);
 image.setColorTable(myColorTable);

QImage::QImage ( uchar * data, int width, int height, int depth, int bytesPerLine, const QRgb * colortable, int numColors, Endian bitOrder )

Constructs an image with the given width, height, depth, bytesPerLine, colortable, numColors and bitOrder, that uses an existing memory buffer, data. The image does not delete the buffer at destruction.

Warning: This constructor is only available in Qtopia Core.

The data has to be 32-bit aligned, and each scanline of data in the image must also be 32-bit aligned, so it's no longer possible to specify a custom bytesPerLine value.

QImage::QImage ( const QByteArray & data )

Use the static fromData() function instead.

For example, if you have code like

 QByteArray data;
 ...
 QImage image(data);

you can rewrite it as

 QByteArray data;
 ...
 QImage image = QImage::fromData(data);

Endian QImage::bitOrder () const

Returns the bit order for the image. If it is a 1-bpp image, this function returns either QImage::BigEndian or QImage::LittleEndian. Otherwise, this function returns QImage::IgnoreEndian.

Use the format() function instead for the monochrome formats. For non-monochrome formats the bit order is irrelevant.

QImage QImage::convertBitOrder ( Endian bitOrder ) const

Converts the bit order of the image to the given bitOrder and returns the converted image. The original image is not changed. Returns this image if the given bitOrder is equal to the image current bit order, or a null image if this image cannot be converted.

Use convertToFormat() instead.

QImage QImage::convertDepth ( int depth, Qt::ImageConversionFlags flags = Qt::AutoColor ) const

Converts the depth (bpp) of the image to the given depth and returns the converted image. The original image is not changed. Returns this image if depth is equal to the image depth, or a null image if this image cannot be converted. The depth argument must be 1, 8 or 32. If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the flags to specify how you'd prefer this to happen.

Use the convertToFormat() function instead.

QImage QImage::convertDepthWithPalette ( int depth, QRgb * palette, int palette_count, Qt::ImageConversionFlags flags = Qt::AutoColor ) const

Returns an image with the given depth, using the palette_count colors pointed to by palette. If depth is 1 or 8, the returned image will have its color table ordered in the same way as palette.

If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the flags to specify how you'd prefer this to happen.

Note: currently no closest-color search is made. If colors are found that are not in the palette, the palette may not be used at all. This result should not be considered valid because it may change in future implementations.

Currently inefficient for non-32-bit images.

Use the convertToFormat() function in combination with the setColorTable() function instead.

QImage QImage::copy ( int x, int y, int w, int h, Qt::ImageConversionFlags flags ) const

This is an overloaded member function, provided for convenience.

Use copy() instead.

QImage QImage::copy ( const QRect & rect, Qt::ImageConversionFlags flags ) const

This is an overloaded member function, provided for convenience.

Use copy() instead.

bool QImage::create ( int width, int height, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )

Sets the image width, height, depth, its number of colors (in numColors), and bit order. Returns true if successful, or false if the parameters are incorrect or if memory cannot be allocated.

The width and height is limited to 32767. depth must be 1, 8, or 32. If depth is 1, bitOrder must be set to either QImage::LittleEndian or QImage::BigEndian. For other depths bitOrder must be QImage::IgnoreEndian.

This function allocates a color table and a buffer for the image data. The image data is not initialized. The image buffer is allocated as a single block that consists of a table of scanLine() pointers (jumpTable()) and the image data (bits()).

Use a QImage constructor instead.

bool QImage::create ( const QSize & size, int depth, int numColors = 0, Endian bitOrder = IgnoreEndian )

This is an overloaded member function, provided for convenience.

The width and height are specified in the size argument.

Use a QImage constructor instead.

bool QImage::hasAlphaBuffer () const

Returns true if alpha buffer mode is enabled; otherwise returns false.

Use the hasAlphaChannel() function instead.

void QImage::invertPixels ( bool invertAlpha )

This is an overloaded member function, provided for convenience.

Use the invertPixels() function that takes a QImage::InvertMode parameter instead.

uchar ** QImage::jumpTable ()

Returns a pointer to the scanline pointer table. This is the beginning of the data block for the image.

Use the bits() or scanLine() function instead.

const uchar * const * QImage::jumpTable () const

This is an overloaded member function, provided for convenience.

QImage QImage::mirror ( bool horizontal = false, bool vertical = true ) const

Use mirrored() instead.

void QImage::reset ()

Resets all image parameters and deallocates the image data.

Assign a null image instead.

For example, if you have code like

 QImage image;
 image.reset();

you can rewrite it as

 QImage image;
 image = QImage();

QImage QImage::scaleHeight ( int h ) const

Use scaledToHeight() instead.

QImage QImage::scaleWidth ( int w ) const

Use scaledToWidth() instead.

void QImage::setAlphaBuffer ( bool enable )

Enables alpha buffer mode if enable is true, otherwise disables it. The alpha buffer is used to set a mask when a QImage is translated to a QPixmap.

If a monochrome or indexed 8-bit image has alpha channels in their color tables they will automatically detect that they have an alpha channel, so this function is not required. To force alpha channels on 32-bit images, use the convertToFormat() function.

See also hasAlphaBuffer().

QImage QImage::smoothScale ( int width, int height, Qt::AspectRatioMode mode = Qt::IgnoreAspectRatio ) const

Use scaled() instead.

For example, if you have code like

 QImage image;
 image.smoothScale(width, height, mode);

you can rewrite it as

 QImage image;
 image.scaled(width, height, mode, Qt::SmoothTransformation);

QImage QImage::smoothScale ( const QSize & size, Qt::AspectRatioMode mode = Qt::IgnoreAspectRatio ) const

This is an overloaded member function, provided for convenience.

Use scaled() instead.

For example, if you have code like

 QImage image;
 image.smoothScale(size, mode);

you can rewrite it as

 QImage image;
 image.scaled(size, mode, Qt::SmoothTransformation);

QImage QImage::swapRGB () const

Use rgbSwapped() instead.

Endian QImage::systemBitOrder ()   [static]

Determines the bit order of the display hardware. Returns QImage::LittleEndian (LSB first) or QImage::BigEndian (MSB first).

This function is no longer relevant for QImage. Use QSysInfo instead.

Endian QImage::systemByteOrder ()   [static]

Determines the host computer byte order. Returns QImage::LittleEndian (LSB first) or QImage::BigEndian (MSB first).

This function is no longer relevant for QImage. Use QSysInfo instead.

QImage QImage::xForm ( const QMatrix & matrix ) const

Use transformed() instead.

For example, if you have code like

 QImage image;
 ...
 image.xForm(matrix);

you can rewrite it as

 QImage image;
 ...
 image.transformed(matrix);

Related Non-Members

void bitBlt ( QImage * dst, int dx, int dy, const QImage * src, int sx = 0, int sy = 0, int sw = -1, int sh = -1, Qt::ImageConversionFlags flags = Qt::AutoColor )

Copies a block of pixels from src to dst. The pixels copied from source (src) are converted according to flags if it is incompatible with the destination (dst).

sx, sy is the top-left pixel in src, dx, dy is the top-left position in dst and sw, sh is the size of the copied block. The copying is clipped if areas outside src or dst are specified. If sw is -1, it is adjusted to src->width(). Similarly, if sh is -1, it is adjusted to src->height().

Currently inefficient for non 32-bit images.

Use copy() or QPainter::drawImage() instead.


Copyright © 2007 Trolltech Trademarks
Qt 4.2.3