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.
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.
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.
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.
QImage provides a collection of functions that can be used to obtain a variety of information about the image:
|Geometry||The size(), width(), height(), dotsPerMeterX(), and dotsPerMeterY() functions provide information about the image size and aspect ratio.The rect() function returns the image’s enclosing rectangle. The valid() function tells if a given pair of coordinates is within this rectangle. The offset() function returns the number of pixels by which the image is intended to be offset by when positioned relative to other images, which also can be manipulated using the setOffset() function.|
|Colors||The color of a pixel can be retrieved by passing its coordinates to the pixel() function. The pixel() function returns the color as a QRgb value indepedent of the image’s format.In case of monochrome and 8-bit images, the colorCount() and colorTable() functions provide information about the color components used to store the image data: The colorTable() function returns the image’s entire color table. To obtain a single entry, use the pixelIndex() function to retrieve the pixel index for a given pair of coordinates, then use the color() function to retrieve the color. Note that if you create an 8-bit image manually, you have to set a valid color table on the image as well.The hasAlphaChannel() function tells if the image’s format respects the alpha channel, or not. The allGray() and isGrayscale() functions tell whether an image’s colors are all shades of gray.See also the Pixel Manipulation and Image Transformations sections.|
|Text||The text() function returns the image text associated with the given text key. An image’s text keys can be retrieved using the textKeys() function. Use the setText() function to alter an image’s text.|
|Low-level information||The depth() function returns the depth of the image. The supported depths are 1 (monochrome), 8, 16, 24 and 32 bits. The bitPlaneCount() function tells how many of those bits that are used. For more information see the Image Formats section.The format(), bytesPerLine(), and sizeInBytes() functions provide low-level information about the data stored in the image.The cacheKey() function returns a number that uniquely identifies the contents of this QImage object.|
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.
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);
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);
For images with more than 8-bit per color-channel. The methods setPixelColor() and pixelColor() can be used to set and get with QColor values.
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
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.
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.
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.
createMaskFromColor to get mask for specific color
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, and the rgbSwapped() function constructs a BGR image from a RGB image.
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:
|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.|
|setColorCount()||Resizes the color table. Only monochrome and 8-bit formats.|
copy(QRect) to get copy image for specific region
A QPixmap can easily be displayed on the screen using QLabel or one of QAbstractButton‘s subclasses (such as QPushButton and QToolButton). QLabel has a pixmap property, whereas QAbstractButton has an icon property.
QPixmap objects can be passed around by value since the QPixmap class uses implicit data sharing. For more information, see the Implicit Data Sharing documentation. QPixmap objects can also be streamed.
Note that the pixel data in a pixmap is internal and is managed by the underlying window system. Because QPixmap is a QPaintDevice subclass, QPainter can be used to draw directly onto pixmaps. Pixels can only be accessed through QPainter functions or by converting the QPixmap to a QImage. However, the fill() function is available for initializing the entire pixmap with a given color.
There are functions to convert between QImage and QPixmap. Typically, the QImage class is used to load an image file, optionally manipulating the image data, before the QImage object is converted into a QPixmap to be shown on screen. Alternatively, if no manipulation is desired, the image file can be loaded directly into a QPixmap.
and you can get pixmap from image by using fromImage static function.
QPixmap provides a collection of functions that can be used to obtain a variety of information about the pixmap:
|Geometry||The size(), width() and height() functions provide information about the pixmap’s size. The rect() function returns the image’s enclosing rectangle.|
|Alpha component||The hasAlphaChannel() returns |
|Low-level information||The depth() function returns the depth of the pixmap. The defaultDepth() function returns the default depth, i.e. the depth used by the application on the given screen.The cacheKey() function returns a number that uniquely identifies the contents of the QPixmap object.|
A QPixmap object can be converted into a QImage using the toImage() function. Likewise, a QImage can be converted into a QPixmap using the fromImage(). If this is too expensive an operation, you can use QBitmap::fromImage() instead.
To convert a QPixmap to and from HICON you can use the QtWinExtras functions QtWin::toHICON() and QtWin::fromHICON() respectively.
QPixmap supports a number of functions for creating a new pixmap that is a transformed version of the original:
The scaled(), scaledToWidth() and scaledToHeight() functions return scaled copies of the pixmap, while the copy() function creates a QPixmap that is a plain copy of the original one.
The transformed() function returns a copy of the pixmap 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 pixmap containing all transformed points of the original pixmap. The static trueMatrix() function returns the actual matrix used for transforming the pixmap.
//heuristic mask QPixmap myPixmap; myPixmap.setMask(myPixmap.createHeuristicMask());
//save pixmap QPixmap pixmap; QByteArray bytes; QBuffer buffer(&bytes); buffer.open(QIODevice::WriteOnly); pixmap.save(&buffer, "PNG"); // writes pixmap into bytes in PNG format
//scroll pixels QLabel label; QPixmap pixmap("C:/Users/moham/OneDrive/Pictures/Capture.PNG"); pixmap.scroll(100,100,QRect(100,100,400,400));//copy rect and offset it label.setPixmap(pixmap); label.show();
//transform QLabel label; QPixmap pixmap("C:/Users/moham/OneDrive/Pictures/Capture.PNG"); QPixmap pixmap2=pixmap.transformed(QTransform::fromScale(2,2)); label.setPixmap(pixmap2); label.show();
QFont , QFontMetric
QFont can be regarded as a query for one or more fonts on the system.
When you create a QFont object you specify various attributes that you want the font to have. Qt will use the font with the specified attributes, or if no matching font exists, Qt will use the closest matching installed font. The attributes of the font that is actually used are retrievable from a QFontInfo object. If the window system provides an exact match exactMatch() returns
true. Use QFontMetricsF to get measurements, e.g. the pixel length of a string using QFontMetrics::width().
Attributes which are not specifically set will not affect the font selection algorithm, and default values will be preferred instead.
To load a specific physical font, typically represented by a single file, use QRawFont instead.
Note that a QGuiApplication instance must exist before a QFont can be used. You can set the application’s default font with QGuiApplication::setFont().
If a chosen font does not include all the characters that need to be displayed, QFont will try to find the characters in the nearest equivalent fonts. When a QPainter draws a character from a font the QFont will report whether or not it has the character; if it does not, QPainter will draw an unfilled square.
QFont serifFont("Times", 10, QFont::Bold); QFont sansFont("Helvetica [Cronyx]", 12);
The attributes set in the constructor can also be set later, e.g. setFamily(), setPointSize(), setPointSizeF(), setWeight() and setItalic(). The remaining attributes must be set after contstruction, e.g. setBold(), setUnderline(), setOverline(), setStrikeOut() and setFixedPitch(). QFontInfo objects should be created after the font’s attributes have been set. A QFontInfo object will not change, even if you change the font’s attributes. The corresponding “get” functions, e.g. family(), pointSize(), etc., return the values that were set, even though the values used may differ. The actual values are available from a QFontInfo object.
If the requested font family is unavailable you can influence the font matching algorithm by choosing a particular QFont::StyleHint and QFont::StyleStrategy with setStyleHint(). The default family (corresponding to the current style hint) is returned by defaultFamily().
You can provide substitutions for font family names using insertSubstitution() and insertSubstitutions(). Substitutions can be removed with removeSubstitutions(). Use substitute() to retrieve a family’s first substitute, or the family name itself if it has no substitutes. Use substitutes() to retrieve a list of a family’s substitutes (which may be empty). After substituting a font, you must trigger the updating of the font by destroying and re-creating all QFont objects.
Every QFont has a key() which you can use, for example, as the key in a cache or dictionary. If you want to store a user’s font preferences you could use QSettings, writing the font information with toString() and reading it back with fromString(). The operator<<() and operator>>() functions are also available, but they work on a data stream.
It is possible to set the height of characters shown on the screen to a specified number of pixels with setPixelSize(); however using setPointSize() has a similar effect and provides device independence.
The font matching algorithm works as follows:
- The specified font families (set by setFamilies()) are searched for.
- If not found, then if set the specified font family exists and can be used to represent the writing system in use, it will be selected.
- If not, a replacement font that supports the writing system is selected. The font matching algorithm will try to find the best match for all the properties set in the QFont. How this is done varies from platform to platform.
- If no font exists on the system that can support the text, then special “missing character” boxes will be shown in its place.
Note: If the selected font, though supporting the writing system in general, is missing glyphs for one or more specific characters, then Qt will try to find a fallback font for this or these particular characters. This feature can be disabled using QFont::NoFontMerging style strategy.
In Windows a request for the “Courier” font is automatically changed to “Courier New”, an improved version of Courier that allows for smooth scaling. The older “Courier” bitmap font can be selected by setting the PreferBitmap style strategy (see setStyleStrategy()).
Once a font is found, the remaining attributes are matched in order of priority:
- pointSize() (see below)
If you have a font which matches on family, even if none of the other attributes match, this font will be chosen in preference to a font which doesn’t match on family but which does match on the other attributes. This is because font family is the dominant search criteria.
The point size is defined to match if it is within 20% of the requested point size. When several fonts match and are only distinguished by point size, the font with the closest point size to the one requested will be chosen.
The actual family, font size, weight and other font attributes used for drawing text will depend on what’s available for the chosen family under the window system. A QFontInfo object can be used to determine the actual values used for drawing the text.
QFontMetrics fm(f1); int textWidthInPixels = fm.horizontalAdvance("How many pixels wide is this text?"); int textHeightInPixels = fm.height(); QRect rect = fm.boundingRect("hello");
QFontDatabase : The most common uses of this class are to query the database for the list of font families() and for the pointSizes() and styles() that are available for each family. An alternative to pointSizes() is smoothSizes() which returns the sizes at which a given family and style will look attractive.
addApplicationFont , addApplicationFontFromData to load font file