I am trying to create images from text using QImage.
As per the documentation here: http://doc.qt.io/qt-5/qimage.html#Format-enum
We cannot use QImage::Format_Indexed8
with QImage.
I cannot use QImage::Format_Mono
or QImage::Format_MonoLSB
due to its low quality.
My question is:
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.
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.
There isn't a widget specifically made for displaying images, but this can be done with the label widget. We do this with the pixmap property. QPixmap pic("/path/to/your/image"); ui->label->setPixmap(pic);
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.
Here is a sample code that does it:
QImage image(100, 50, QImage::Format_ARGB32_Premultiplied);
QPainter painter(&image);
painter.fillRect(image.rect(), Qt::yellow);
painter.drawText(image.rect(), Qt::AlignCenter | Qt::AlignVCenter, "hello, world");
image.save("output.png");
It creates this image:
The output format is PNG, so it will have good compression without losing any quality.
There's this example, which shows you how to use QPainter::drawText
and work with fonts:
http://doc.qt.io/archives/qt-4.7/painting-fontsampler.html
QImage::save
has support for a variety of formats and quality levels:
http://doc.qt.io/archives/qt-4.7/qimage.html#reading-and-writing-image-files
Although QImage
is in QtCore, QPainter
and the text drawing routines are in QtGUI. So on a Linux system this will require an X server to be running:
http://www.qtcentre.org/threads/1758-QPainter-in-console-apps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With