There is a picture in bmp format I open it with the help of the file selection dialog, I need to convert it to jpg format using qt tools, how to do it? Further, by pressing the "display on form" button, a jpg image is displayed in the widget.
1 answer
JPG is a file container, plus a codec. Before displaying the jpeg image, the data is converted into one of the convenient formats for drawing. The same with BMP .
You can open any of the supported image file formats like this:
QImage img("my_image.bmp"); Save a previously opened file to another format like this:
img.save("my_image.jpg"); The easiest way to draw a QImage on a widget is using a QLabel :
QLabel *label = new QLabel(this); label->setPixmap(QPixmap::fromImage(img)); ... or without a QImage :
QLabel *label = new QLabel(this); label->setPixmap(QPixmap("my_image.bmp")); If you want to paint on the background of an arbitrary widget, you need to override the QWidget::paintEvent() event:
void MyWidget::paintEvent(QPaintEvent *event) { QPixmap pix("my_image.bmp"); if(pix.isNull() == false) { QRect dst_rc = rect(); if(dst_rc.width() > dst_rc.height()) pix = pix.scaledToHeight(dst_rc.height()); else if(dst_rc.height() > dst_rc.width()) pix = pix.scaledToWidth(dst_rc.width()); dst_rc = pix.rect(); dst_rc.moveCenter(rect().center()); QPainter painter(this); painter.drawPixmap(dst_rc, pix); } event->accept(); } Addition
It is better not to load the image file directly into paintEvent() , since this operation can be noticeably expensive, and it will be done every time you redraw the widget. It is better to put this in a separate method of the class of the widget, which takes the name of the file as an attribute.
Alternatively, you can use the cache:
void MyWidget::paintEvent(QPaintEvent *event) { const QString fname("my_image.bmp"); QPixmap pix; if(QPixmapCache::find(fname, &pix) == false) { pix.load(fname); if(pix.isNull() == false) { QRect dst_rc = rect(); if(dst_rc.width() > dst_rc.height()) pix = pix.scaledToHeight(dst_rc.height()); else if(dst_rc.height() > dst_rc.width()) pix = pix.scaledToWidth(dst_rc.width()); QPixmapCache::insert(fname, pix); } } if(pix.isNull() == false) { QRect dst_rc = pix.rect(); dst_rc.moveCenter(rect().center()); QPainter painter(this); painter.drawPixmap(dst_rc, pix); } event->accept(); } In the cache code version, the image will be loaded and converted to the size of the widget only once. Further, while the cache is alive, it will only be drawn, which of course will save resources.
Just in case, I note that the objects in the global static QPixmapCache live for no more than 30 seconds. If this does not suit you, then you can use QCache or something derived from it.
- Thank you, then it is just planned to transmit jpg image and messages on the socket to the client, but this is a separate topic. - Disastricks
- @Disastricks, please. Create a new question if there is a problem with something. - alexis031182