Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating textual images using QImage (qt)

Tags:

c++

qt

qimage

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:

  • What is the best way to create textual image (batch processing) so that we can get decent quality with minimum file size?
  • Is there is any way to do image compression through QT once the image is created to reduce the file size?
like image 689
Gurpreet Singh Avatar asked Sep 24 '11 10:09

Gurpreet Singh


People also ask

What is QImage in Qt?

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.

How do you convert QImage to QPixmap?

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.

How do I display an image in Qt widget?

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);

What is a QImage?

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.


2 Answers

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:

enter image description here

The output format is PNG, so it will have good compression without losing any quality.

like image 157
sashoalm Avatar answered Sep 19 '22 02:09

sashoalm


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

like image 35
HostileFork says dont trust SE Avatar answered Sep 19 '22 02:09

HostileFork says dont trust SE