Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

QImage Class

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

Header:#include <QImage>
Inherits:QPaintDevice

Note: All functions in this class arereentrant.

Public Types

enumFormat { Format_Invalid, Format_Mono, Format_MonoLSB, Format_Indexed8, ..., Format_ARGB4444_Premultiplied }
enumInvertMode { InvertRgb, InvertRgba }

Public Functions

QImage()
QImage(const QSize & size, Format format)
QImage(int width, int height, Format format)
QImage(uchar * data, int width, int height, Format format)
QImage(const uchar * data, int width, int height, Format format)
QImage(uchar * data, int width, int height, int bytesPerLine, Format format)
QImage(const uchar * data, int width, int height, int bytesPerLine, Format format)
QImage(const char * const[] xpm)
QImage(const QString & fileName, const char * format = 0)
QImage(const char * fileName, const char * format = 0)
QImage(const QImage & image)
~QImage()
boolallGray() const
intbitPlaneCount() const
uchar *bits()
const uchar *bits() const
intbyteCount() const
intbytesPerLine() const
qint64cacheKey() const
QRgbcolor(int i) const
intcolorCount() const
QVector<QRgb>colorTable() const
const uchar *constBits() const
const uchar *constScanLine(int i) const
QImageconvertToFormat(Format format, Qt::ImageConversionFlags flags = Qt::AutoColor) const
QImageconvertToFormat(Format format, const QVector<QRgb> & colorTable, Qt::ImageConversionFlags flags = Qt::AutoColor) const
QImagecopy(const QRect & rectangle = QRect()) const
QImagecopy(int x, int y, int width, int height) const
QImagecreateAlphaMask(Qt::ImageConversionFlags flags = Qt::AutoColor) const
QImagecreateHeuristicMask(bool clipTight = true) const
QImagecreateMaskFromColor(QRgb color, Qt::MaskMode mode = Qt::MaskInColor) const
intdepth() const
intdotsPerMeterX() const
intdotsPerMeterY() const
voidfill(uint pixelValue)
voidfill(Qt::GlobalColor color)
voidfill(const QColor & color)
Formatformat() const
boolhasAlphaChannel() const
intheight() const
voidinvertPixels(InvertMode mode = InvertRgb)
boolisGrayscale() const
boolisNull() const
boolload(const QString & fileName, const char * format = 0)
boolload(QIODevice * device, const char * format)
boolloadFromData(const uchar * data, int len, const char * format = 0)
boolloadFromData(const QByteArray & data, const char * format = 0)
QImagemirrored(bool horizontal = false, bool vertical = true) const
QPointoffset() const
QRgbpixel(const QPoint & position) const
QRgbpixel(int x, int y) const
intpixelIndex(const QPoint & position) const
intpixelIndex(int x, int y) const
QRectrect() const
QImagergbSwapped() const
boolsave(const QString & fileName, const char * format = 0, int quality = -1) const
boolsave(QIODevice * device, const char * format = 0, int quality = -1) const
QImagescaled(const QSize & size, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio, Qt::TransformationMode transformMode = Qt::FastTransformation) const
QImagescaled(int width, int height, Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio, Qt::TransformationMode transformMode = Qt::FastTransformation) const
QImagescaledToHeight(int height, Qt::TransformationMode mode = Qt::FastTransformation) const
QImagescaledToWidth(int width, Qt::TransformationMode mode = Qt::FastTransformation) const
uchar *scanLine(int i)
const uchar *scanLine(int i) const
voidsetColor(int index, QRgb colorValue)
voidsetColorCount(int colorCount)
voidsetColorTable(const QVector<QRgb> colors)
voidsetDotsPerMeterX(int x)
voidsetDotsPerMeterY(int y)
voidsetOffset(const QPoint & offset)
voidsetPixel(const QPoint & position, uint index_or_rgb)
voidsetPixel(int x, int y, uint index_or_rgb)
voidsetText(const QString & key, const QString & text)
QSizesize() const
voidswap(QImage & other)
QStringtext(const QString & key = QString()) const
QStringListtextKeys() const
QImagetransformed(const QMatrix & matrix, Qt::TransformationMode mode = Qt::FastTransformation) const
QImagetransformed(const QTransform & matrix, Qt::TransformationMode mode = Qt::FastTransformation) const
boolvalid(const QPoint & pos) const
boolvalid(int x, int y) const
intwidth() const
operator QVariant() const
booloperator!=(const QImage & image) const
QImage &operator=(const QImage & image)
QImage &operator=(QImage && other)
booloperator==(const QImage & image) const

Static Public Members

QImagefromData(const uchar * data, int size, const char * format = 0)
QImagefromData(const QByteArray & data, const char * format = 0)
QMatrixtrueMatrix(const QMatrix & matrix, int width, int height)
QTransformtrueMatrix(const QTransform & matrix, int width, int height)

Related Non-Members

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

Additional Inherited Members

Detailed Description

TheQImage 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 andQPicture.QImage is designed and optimized for I/O, and for direct pixel access and manipulation, whileQPixmap is designed and optimized for showing images on screen.QBitmap is only a convenience class that inheritsQPixmap, ensuring a depth of 1. Finally, theQPicture class is a paint device that records and replaysQPainter commands.

BecauseQImage is aQPaintDevice subclass,QPainter can be used to draw directly onto images. When usingQPainter on aQImage, the painting can be performed in another thread than the current GUI thread.

TheQImage class supports several image formats described by theFormat enum. These include monochrome, 8-bit, 32-bit and alpha-blended images which are available in all versions of Qt 4.x.

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 theQImage class usesimplicit data sharing.QImage objects can also be streamed and compared.

Note:If you would like to loadQImage objects in a static build of Qt, refer to thePlugin HowTo.

Warning: Painting on aQImage with the formatQImage::Format_Indexed8 is not supported.

Reading and Writing Image Files

QImage provides several ways of loading an image file: The file can be loaded when constructing theQImage object, or by using theload() orloadFromData() functions later on.QImage also provides the staticfromData() function, constructing aQImage 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. SeeThe Qt Resource System overview for details on how to embed images and other resource files in the application's executable.

Simply call thesave() function to save aQImage object.

The complete list of supported file formats are available through theQImageReader::supportedImageFormats() andQImageWriter::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
TIFFTagged Image File FormatRead/write
XBMX11 BitmapRead/write
XPMX11 PixmapRead/write

Image Information

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

Available Functions
GeometryThesize(),width(),height(),dotsPerMeterX(), anddotsPerMeterY() functions provide information about the image size and aspect ratio.

Therect() function returns the image's enclosing rectangle. Thevalid() function tells if a given pair of coordinates is within this rectangle. Theoffset() 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 thesetOffset() function.

ColorsThe color of a pixel can be retrieved by passing its coordinates to thepixel() function. Thepixel() function returns the color as aQRgb value indepedent of the image's format.

In case of monochrome and 8-bit images, thecolorCount() andcolorTable() functions provide information about the color components used to store the image data: ThecolorTable() function returns the image's entire color table. To obtain a single entry, use thepixelIndex() function to retrieve the pixel index for a given pair of coordinates, then use thecolor() 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.

ThehasAlphaChannel() function tells if the image's format respects the alpha channel, or not. TheallGray() andisGrayscale() functions tell whether an image's colors are all shades of gray.

See also thePixel Manipulation andImage Transformations sections.

TextThetext() function returns the image text associated with the given text key. An image's text keys can be retrieved using thetextKeys() function. Use thesetText() function to alter an image's text.
Low-level informationThedepth() function returns the depth of the image. The supported depths are 1 (monochrome), 8, 16, 24 and 32 bits. ThebitPlaneCount() function tells how many of those bits that are used. For more information see theImage Formats section.

Theformat(),bytesPerLine(), andbyteCount() functions provide low-level information about the data stored in the image.

ThecacheKey() function returns a number that uniquely identifies the contents of thisQImage 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 theImage Formats section.

In case of a 32-bit image, thesetPixel() 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 suitableQRgb value, use theqRgb() (adding a default alpha component to the given RGB values, i.e. creating an opaque color) orqRgba() function. For example:

32-bit
QImage image(3,3,QImage::Format_RGB32);QRgb value;value=qRgb(189,149,39);// 0xffbd9527image.setPixel(1,1, value);value=qRgb(122,163,39);// 0xff7aa327image.setPixel(0,1, value);image.setPixel(1,0, value);value=qRgb(237,187,51);// 0xffedba31image.setPixel(2,1, value);

In case of a 8-bit and monchrome images, the pixel value is only an index from the image's color table. So thesetPixel() 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 thesetColor() function.

An entry in the color table is an ARGB quadruplet encoded as anQRgb value. Use theqRgb() andqRgba() functions to make a suitableQRgb value for use with thesetColor() function. For example:

8-bit
QImage image(3,3,QImage::Format_Indexed8);QRgb value;value=qRgb(122,163,39);// 0xff7aa327image.setColor(0, value);value=qRgb(237,187,51);// 0xffedba31image.setColor(1, value);value=qRgb(189,149,39);// 0xffbd9527image.setColor(2, value);image.setPixel(0,1,0);image.setPixel(1,0,0);image.setPixel(1,1,2);image.setPixel(2,1,1);

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

Image Formats

Each pixel stored in aQImage is represented by an integer. The size of the integer varies depending on the format.QImage supports several image formats described by theFormat 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 aQVector<QRgb>, and theQRgb 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 anQRgb 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 theformat() function. Use theconvertToFormat() functions to convert an image into another format. TheallGray() andisGrayscale() 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: ThecreateAlphaMask() function builds and returns a 1-bpp mask from the alpha buffer in this image, and thecreateHeuristicMask() 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.

Themirrored() function returns a mirror of the image in the desired direction, thescaled() returns a copy of the image scaled to a rectangle of the desired measures, and thergbSwapped() function constructs a BGR image from a RGB image.

ThescaledToWidth() andscaledToHeight() functions return scaled copies of the image.

Thetransformed() 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 statictrueMatrix() function returns the actual matrix used for transforming the image.

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

FunctionDescription
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 givenInvertMode value.
setColorTable()Sets the color table used to translate color indexes. Only monochrome and 8-bit formats.
setColorCount()Resizes the color table. Only monochrome and 8-bit formats.

Legal Information

For smooth scaling, thetransformed() 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 alsoQImageReader,QImageWriter,QPixmap,QSvgRenderer,Image Composition Example,Image Viewer Example,Scribble Example, andPixelator Example.

Member Type Documentation

enum QImage::Format

The following image formats are available in Qt. Values greater than QImage::Format_RGB16 were added in Qt 4.4. See the notes after the table.

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.
QImage::Format_RGB167The image is stored using a 16-bit RGB format (5-6-5).
QImage::Format_ARGB8565_Premultiplied8The image is stored using a premultiplied 24-bit ARGB format (8-5-6-5).
QImage::Format_RGB6669The image is stored using a 24-bit RGB format (6-6-6). The unused most significant bits is always zero.
QImage::Format_ARGB6666_Premultiplied10The image is stored using a premultiplied 24-bit ARGB format (6-6-6-6).
QImage::Format_RGB55511The image is stored using a 16-bit RGB format (5-5-5). The unused most significant bit is always zero.
QImage::Format_ARGB8555_Premultiplied12The image is stored using a premultiplied 24-bit ARGB format (8-5-5-5).
QImage::Format_RGB88813The image is stored using a 24-bit RGB format (8-8-8).
QImage::Format_RGB44414The image is stored using a 16-bit RGB format (4-4-4). The unused bits are always zero.
QImage::Format_ARGB4444_Premultiplied15The image is stored using a premultiplied 16-bit ARGB format (4-4-4-4).

Note:Drawing into aQImage with QImage::Format_Indexed8 is not supported.

Note:Do not render into ARGB32 images usingQPainter. Using QImage::Format_ARGB32_Premultiplied is significantly faster.

See alsoformat() andconvertToFormat().

enum QImage::InvertMode

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

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

See alsoinvertPixels().

Member Function Documentation

QImage::QImage()

Constructs a null image.

See alsoisNull().

QImage::QImage(constQSize & size,Format format)

Constructs an image with the givensize andformat.

Anull image is returned if memory cannot be allocated.

Warning: This will create aQImage with uninitialized data. Callfill() to fill the image with an appropriate pixel value before drawing onto it withQPainter.

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

Constructs an image with the givenwidth,height andformat.

Anull image will be returned if memory cannot be allocated.

Warning: This will create aQImage with uninitialized data. Callfill() to fill the image with an appropriate pixel value before drawing onto it withQPainter.

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

Constructs an image with the givenwidth,height andformat, that uses an existing memory buffer,data. Thewidth andheight 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 theQImage. The image does not delete the buffer at destruction.

Ifformat is an indexed color format, the image color table is initially empty and must be sufficiently expanded withsetColorCount() orsetColorTable() before the image is used.

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

Constructs an image with the givenwidth,height andformat, that uses an existing read-only memory buffer,data. Thewidth andheight 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 theQImage and all copies that have not been modified or otherwise detached from the original buffer. The image does not delete the buffer at destruction.

Ifformat is an indexed color format, the image color table is initially empty and must be sufficiently expanded withsetColorCount() orsetColorTable() before the image is used.

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

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

Constructs an image with the givenwidth,height andformat, that uses an existing memory buffer,data. Thewidth andheight must be specified in pixels.bytesPerLine specifies the number of bytes per line (stride).

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

Ifformat is an indexed color format, the image color table is initially empty and must be sufficiently expanded withsetColorCount() orsetColorTable() before the image is used.

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

Constructs an image with the givenwidth,height andformat, that uses an existing memory buffer,data. Thewidth andheight must be specified in pixels.bytesPerLine specifies the number of bytes per line (stride).

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

Ifformat is an indexed color format, the image color table is initially empty and must be sufficiently expanded withsetColorCount() orsetColorTable() before the image is used.

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

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

Constructs an image from the givenxpm 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:

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

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

QImage::QImage(constQString & fileName, constchar * format = 0)

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

The loader attempts to read the image using the specifiedformat. If theformat 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 theResource System overview for details on how to embed images and other resource files in the application's executable.

See alsoisNull() andReading and Writing Image Files.

QImage::QImage(constchar * fileName, constchar * format = 0)

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

The loader attempts to read the image using the specifiedformat. If theformat 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 theResource System overview for details on how to embed images and other resource files in the application's executable.

You can disable this constructor by definingQT_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 throughQObject::tr().

See alsoQString::fromAscii(),isNull(), andReading and Writing Image Files.

QImage::QImage(constQImage & image)

Constructs a shallow copy of the givenimage.

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

See alsocopy().

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 alsoisGrayscale().

int QImage::bitPlaneCount() const

Returns the number of bit planes in the image.

The number of bit planes is the number of bits of color and transparency information for each pixel. This is different from (i.e. smaller than) the depth when the image format contains unused bits.

This function was introduced in Qt 4.7.

See alsodepth(),format(), andImage Formats.

uchar * QImage::bits()

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

Note thatQImage usesimplicit data sharing. This function performs a deep copy of the shared pixel data, thus ensuring that thisQImage is the only one using the current return value.

See alsoscanLine(),byteCount(), andconstBits().

constuchar * QImage::bits() const

This is an overloaded function.

Note thatQImage usesimplicit data sharing, but this function doesnot perform a deep copy of the shared pixel data, because the returned data is const.

int QImage::byteCount() const

Returns the number of bytes occupied by the image data.

This function was introduced in Qt 4.6.

See alsobytesPerLine(),bits(), andImage Information.

int QImage::bytesPerLine() const

Returns the number of bytes per image scanline.

This is equivalent tobyteCount() /height().

See alsoscanLine().

qint64 QImage::cacheKey() const

Returns a number that identifies the contents of thisQImage object. DistinctQImage objects can only have the same key if they refer to the same contents.

The key will change when the image is altered.

QRgb QImage::color(int i) const

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

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

See alsosetColor(),pixelIndex(), andPixel Manipulation.

int QImage::colorCount() const

Returns the size of the color table for the image.

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

This function was introduced in Qt 4.6.

See alsosetColorCount() andImage Information.

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 alsosetColorTable(),colorCount(), andcolor().

constuchar * QImage::constBits() const

Returns a pointer to the first pixel data.

Note thatQImage usesimplicit data sharing, but this function doesnot perform a deep copy of the shared pixel data, because the returned data is const.

This function was introduced in Qt 4.7.

See alsobits() andconstScanLine().

constuchar * QImage::constScanLine(int i) const

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

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

Note thatQImage usesimplicit data sharing, but this function doesnot perform a deep copy of the shared pixel data, because the returned data is const.

This function was introduced in Qt 4.7.

See alsoscanLine() andconstBits().

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

Returns a copy of the image in the givenformat.

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

See alsoImage Format.

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

This is an overloaded function.

Returns a copy of the image converted to the givenformat, using the specifiedcolorTable.

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(constQRect & 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 givenrectangle.

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 meansQt::color0.

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

See alsoQImage().

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

This is an overloaded function.

The returned image is copied from the position (x,y) in this image, and will always have the givenwidth andheight. 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 isQImage::Format_RGB32.

Theflags argument is a bitwise-OR of theQt::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 isQImage::Format_MonoLSB), which you can convert to big-endian (QImage::Format_Mono) using theconvertToFormat() function.

See alsocreateHeuristicMask() andImage 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 isQImage::Format_MonoLSB), which you can convert to big-endian (QImage::Format_Mono) using theconvertToFormat() function.

IfclipTight 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 alsocreateAlphaMask() andImage Transformations.

QImage QImage::createMaskFromColor(QRgb color,Qt::MaskMode mode = Qt::MaskInColor) const

Creates and returns a mask for this image based on the givencolor value. If themode is MaskInColor (the default value), all pixels matchingcolor will be opaque pixels in the mask. Ifmode is MaskOutColor, all pixels matching the given color will be transparent.

See alsocreateAlphaMask() andcreateHeuristicMask().

int QImage::depth() const

Returns the depth of the image.

The image depth is the number of bits used to store a single pixel, also called bits per pixel (bpp).

The supported depths are 1, 8, 16, 24 and 32.

See alsobitPlaneCount(),convertToFormat(),Image Formats, andImage Information.

int QImage::dotsPerMeterX() const

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

See alsosetDotsPerMeterX() andImage Information.

int QImage::dotsPerMeterY() const

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

See alsosetDotsPerMeterY() andImage Information.

void QImage::fill(uint pixelValue)

Fills the entire image with the givenpixelValue.

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 whileQColor::pixel() returns the pixel value of the underlying window system (essentially an index value), so normally you will want to useQImage::pixel() to use a color from an existing image orQColor::rgb() to use a specific color.

See alsodepth() andImage Transformations.

void QImage::fill(Qt::GlobalColor color)

This is an overloaded function.

Fills the image with the givencolor, described as a standard global color.

This function was introduced in Qt 4.8.

void QImage::fill(constQColor & color)

This is an overloaded function.

Fills the entire image with the givencolor.

If the depth of the image is 1, the image will be filled with 1 ifcolor equalsQt::color1; it will otherwise be filled with 0.

If the depth of the image is 8, the image will be filled with the index corresponding thecolor in the color table if present; it will otherwise be filled with 0.

This function was introduced in Qt 4.8.

Format QImage::format() const

Returns the format of the image.

See alsoImage Formats.

[static]QImage QImage::fromData(constuchar * data,int size, constchar * format = 0)

Constructs aQImage from the firstsize bytes of the given binarydata. The loader attempts to read the image using the specifiedformat. Ifformat is not specified (which is the default), the loader probes the file for a header to guess the file format. binarydata. The loader attempts to read the image, either using the optional imageformat specified or by determining the image format from the data.

Ifformat is not specified (which is the default), the loader probes the file for a header to determine the file format. Ifformat is specified, it must be one of the values returned byQImageReader::supportedImageFormats().

If the loading of the image fails, the image returned will be a null image.

See alsoload(),save(), andReading and Writing Image Files.

[static]QImage QImage::fromData(constQByteArray & data, constchar * format = 0)

This is an overloaded function.

Loads an image from the givenQByteArraydata.

bool QImage::hasAlphaChannel() const

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

See alsoImage Information.

int QImage::height() const

Returns the height of the image.

See alsoImage Information.

void QImage::invertPixels(InvertMode mode = InvertRgb)

Inverts all pixel values in the image.

The given invertmode only have a meaning when the image's depth is 32. The defaultmode isInvertRgb, which leaves the alpha channel unchanged. If themode isInvertRgba, the alpha bits are also inverted.

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

See alsoImage Transformations.

bool QImage::isGrayscale() const

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

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

See alsoallGray() andImage 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(constQString & fileName, constchar * format = 0)

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

The loader attempts to read the image using the specifiedformat, e.g., PNG or JPG. Ifformat 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 theResource System overview for details on how to embed images and other resource files in the application's executable.

See alsoReading and Writing Image Files.

bool QImage::load(QIODevice * device, constchar * format)

This is an overloaded function.

This function reads aQImage from the givendevice. This can, for example, be used to load an image directly into aQByteArray.

bool QImage::loadFromData(constuchar * data,int len, constchar * format = 0)

Loads an image from the firstlen bytes of the given binarydata. Returns true if the image was successfully loaded; otherwise returns false.

The loader attempts to read the image using the specifiedformat, e.g., PNG or JPG. Ifformat is not specified (which is the default), the loader probes the file for a header to guess the file format.

See alsoReading and Writing Image Files.

bool QImage::loadFromData(constQByteArray & data, constchar * format = 0)

This is an overloaded function.

Loads an image from the givenQByteArraydata.

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 whetherhorizontal andvertical are set to true or false.

Note that the original image is not changed.

See alsoImage Transformations.

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 alsosetOffset() andImage Information.

QRgb QImage::pixel(constQPoint & position) const

Returns the color of the pixel at the givenposition.

If theposition is not valid, the results are undefined.

Warning: This function is expensive when used for massive pixel manipulations.

See alsosetPixel(),valid(), andPixel Manipulation.

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

This is an overloaded function.

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

int QImage::pixelIndex(constQPoint & position) const

Returns the pixel index at the givenposition.

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

See alsovalid(),depth(), andPixel Manipulation.

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

This is an overloaded function.

Returns the pixel index at (x,y).

QRect QImage::rect() const

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

See alsoImage Information.

QImage QImage::rgbSwapped() const

Returns aQImage 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 originalQImage is not changed.

See alsoImage Transformations.

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

Saves the image to the file with the givenfileName, using the given image fileformat andquality factor. Ifformat is 0,QImage will attempt to guess the format by looking atfileName's suffix.

Thequality 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 alsoReading and Writing Image Files.

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

This is an overloaded function.

This function writes aQImage to the givendevice.

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

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(constQSize & 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 givensize according to the givenaspectRatioMode andtransformMode.

  • IfaspectRatioMode isQt::IgnoreAspectRatio, the image is scaled tosize.
  • IfaspectRatioMode isQt::KeepAspectRatio, the image is scaled to a rectangle as large as possible insidesize, preserving the aspect ratio.
  • IfaspectRatioMode isQt::KeepAspectRatioByExpanding, the image is scaled to a rectangle as small as possible outsidesize, preserving the aspect ratio.

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

See alsoisNull() andImage Transformations.

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

This is an overloaded function.

Returns a copy of the image scaled to a rectangle with the givenwidth andheight according to the givenaspectRatioMode andtransformMode.

If either thewidth or theheight 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 givenheight using the specified transformationmode.

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

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

See alsoImage 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 givenwidth using the specified transformationmode.

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

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

See alsoImage Transformations.

uchar * QImage::scanLine(int i)

Returns a pointer to the pixel data at the scanline with indexi. 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 toQRgb* (QRgb has a 32-bit size) and use it to read/write the pixel value. You cannot use theuchar* pointer directly, because the pixel format depends on the byte order on the underlying platform. UseqRed(),qGreen(),qBlue(), andqAlpha() to access the pixels.

See alsobytesPerLine(),bits(),Pixel Manipulation, andconstScanLine().

constuchar * QImage::scanLine(int i) const

This is an overloaded function.

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

Sets the color at the givenindex in the color table, to the given tocolorValue. The color value is an ARGB quadruplet.

Ifindex is outside the current size of the color table, it is expanded withsetColorCount().

See alsocolor(),colorCount(),setColorTable(), andPixel Manipulation.

void QImage::setColorCount(int colorCount)

Resizes the color table to containcolorCount entries.

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

When the image is used, the color table must be large enough to have entries for all the pixel/index values present in the image, otherwise the results are undefined.

This function was introduced in Qt 4.6.

See alsocolorCount(),colorTable(),setColor(), andImage Transformations.

void QImage::setColorTable(constQVector<QRgb> colors)

Sets the color table used to translate color indexes toQRgb values, to the specifiedcolors.

When the image is used, the color table must be large enough to have entries for all the pixel/index values present in the image, otherwise the results are undefined.

See alsocolorTable(),setColor(), andImage Transformations.

void QImage::setDotsPerMeterX(int x)

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

Together withdotsPerMeterY(), this number defines the intended scale and aspect ratio of the image, and determines the scale at whichQPainter will draw graphics on the image. It does not change the scale or aspect ratio of the image when it is rendered on other paint devices.

See alsodotsPerMeterX() andImage Information.

void QImage::setDotsPerMeterY(int y)

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

Together withdotsPerMeterX(), this number defines the intended scale and aspect ratio of the image, and determines the scale at whichQPainter will draw graphics on the image. It does not change the scale or aspect ratio of the image when it is rendered on other paint devices.

See alsodotsPerMeterY() andImage Information.

void QImage::setOffset(constQPoint & offset)

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

See alsooffset() andImage Information.

void QImage::setPixel(constQPoint & position,uint index_or_rgb)

Sets the pixel index or color at the givenposition toindex_or_rgb.

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

Ifposition is not a valid coordinate pair in the image, or ifindex_or_rgb >=colorCount() in the case of monochrome and 8-bit images, the result is undefined.

Warning: This function is expensive due to the call of the internaldetach() function called within; if performance is a concern, we recommend the use ofscanLine() to access pixel data directly.

See alsopixel() andPixel Manipulation.

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

This is an overloaded function.

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

void QImage::setText(constQString & key, constQString & text)

Sets the image text to the giventext and associate it with the givenkey.

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 callsave() orQImageWriter::write().

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

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

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

See alsotext() andtextKeys().

QSize QImage::size() const

Returns the size of the image, i.e. itswidth() andheight().

See alsoImage Information.

void QImage::swap(QImage & other)

Swaps imageother with this image. This operation is very fast and never fails.

This function was introduced in Qt 4.8.

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

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

See alsosetText() andtextKeys().

QStringList QImage::textKeys() const

Returns the text keys for this image.

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

See alsotext().

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

Returns a copy of the image that is transformed using the given transformationmatrix and transformationmode.

The transformationmatrix 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 thetrueMatrix() function to retrieve the actual matrix used for transforming an image.

See alsotrueMatrix() andImage Transformations.

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

Returns a copy of the image that is transformed using the given transformationmatrix and transformationmode.

The transformationmatrix 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 thetrueMatrix() function to retrieve the actual matrix used for transforming an image.

Unlike the other overload, this function can be used to perform perspective transformations on images.

See alsotrueMatrix() andImage Transformations.

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

Returns the actual matrix used for transforming an image with the givenwidth,height andmatrix.

When transforming an image using thetransformed() 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 alsotransformed() andImage Transformations.

[static]QTransform QImage::trueMatrix(constQTransform & matrix,int width,int height)

Returns the actual matrix used for transforming an image with the givenwidth,height andmatrix.

When transforming an image using thetransformed() 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.

Unlike the other overload, this function creates transformation matrices that can be used to perform perspective transformations on images.

See alsotransformed() andImage Transformations.

bool QImage::valid(constQPoint & pos) const

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

See alsorect() andQRect::contains().

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

This is an overloaded function.

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

int QImage::width() const

Returns the width of the image.

See alsoImage Information.

QImage::operator QVariant() const

Returns the image as aQVariant.

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

Returns true if this image and the givenimage 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 alsooperator=().

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

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

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

See alsocopy() andQImage().

QImage & QImage::operator=(QImage && other)

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

Returns true if this image and the givenimage 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 alsooperator=().

Related Non-Members

QDataStream &operator<<(QDataStream & stream, constQImage & image)

Writes the givenimage to the givenstream 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 alsoQImage::save() andSerializing Qt Data Types.

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

Reads an image from the givenstream and stores it in the givenimage.

See alsoQImage::load() andSerializing Qt Data Types.

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp