如何将QGraphicsView中的图像保存为bmp/jpg



我是Qt的新手。问题是:在将图像转换为QGraphicsView后,我使用qrubberband来选择图像的裁剪区域。目前选择croppping区域是成功的。但我不知道以后如何将裁剪区域保存为jpg.bmp。请注意,我为GraphicsView制作了一个名为CGraphicsView的ui组件。

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

Qt中有一个特殊的方法。它允许获取视图的屏幕截图。

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

Save()方法可以将图片保存为不同的格式并进行压缩。

同样,使用grabWidget()方法,您也可以获取其他小部件。此外,该方法以QRect为参数,这样您就可以创建所需区域的屏幕截图。

您可以将场景的一部分保存为图像,如:

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

最新更新