user3217504
user3217504

Reputation: 105

How to save an image in a QGraphicsView into a bmp/jpg

I am a newbie for Qt. The question is that: After turning an image into the QGraphicsView, I use a qrubberband to select the cropping area of the image. It is successful to select the croppping region at the moment.But I don't know how to save that cropping region into a jpg/bmp afterwards. Note that I made an ui component for the GraphicsView called CGraphicsView.

void CGraphicsView::mousePressEvent
    ( QMouseEvent* event)
{



 mypoint = event->pos();
 rubberBand = new QRubberBand(QRubberBand::Rectangle, this);//new rectangle band
 rubberBand->setGeometry(QRect(mypoint, QSize()));
 rubberBand->show();


 }

 void CGraphicsView::mouseMoveEvent(QMouseEvent *event)
 {
    if (rubberBand)
 {
 rubberBand->setGeometry(QRect(mypoint, event->pos()).normalized());//Area Bounding
 }
 }

 void CGraphicsView::mouseReleaseEvent(QMouseEvent *event)
 {
  if (rubberBand)
  {
     QRect myRect(mypoint, event->pos());
     rubberBand->hide();// hide on mouse Release
     QImage copyImage;  //<= this Qimage hold nothing
     copyImage = copyImage.copy(myRect);
  }

 }

Upvotes: 2

Views: 1980

Answers (2)

Nejat
Nejat

Reputation: 32655

You can save a part of your scene to an image like :

QPixmap pixmap=QPixmap(myRect.size());
QString filename = QFileDialog::getSaveFileName( this->parentWidget(), tr("Save As"), tr("image.png"));

    if( !filename.isEmpty() )
    {
        QPainter painter( &pixmap );
        painter.setRenderHint(QPainter::Antialiasing);
        scene->render( &painter, pixmap.rect(),myRect, Qt::KeepAspectRatio );
        painter.end();

        pixmap.save(filename,"PNG");
    }

Upvotes: 1

Jablonski
Jablonski

Reputation: 18514

There is special method in Qt. It allows get screenshot of view.

QString fileName = "path";
QPixmap pixMap = QPixmap::grabWidget(graphicsView, rectRegion);
pixMap.save(fileName);

Save() method can save picture in different formats and with compression.

Also with grabWidget() method you can grab another widgets too. Moreover, this method take QRect as argument so you can create screenshot of region what you need.

Upvotes: 1

Related Questions