QVTk截图保存为图片

  先提供一个保存Qimage的版本,其中VTK_MAJOR_VERSION > 8 || (VTK_MAJOR_VERSION == 8 && VTK_MINOR_VERSION >= 1)是为了解决vtk版本问题

QImage GetVTKQImage(QVTKWidget *qvtkWidget)
{
	vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter = vtkSmartPointer<vtkWindowToImageFilter>::New();
	windowToImageFilter->SetInput(qvtkWidget->GetRenderWindow());

	#if VTK_MAJOR_VERSION > 8 || (VTK_MAJOR_VERSION == 8 && VTK_MINOR_VERSION >= 1)
		windowToImageFilter->SetScale(1); //image quality
	#else
		windowToImageFilter->SetMagnification(1); //image quality
	#endif

	windowToImageFilter->SetInputBufferTypeToRGBA(); //also record the alpha (transparency) channel
	windowToImageFilter->ReadFrontBufferOff(); // read from the back buffer
	windowToImageFilter->Update();

	vtkImageData* imageData = windowToImageFilter->GetOutput();
	int width = imageData->GetDimensions()[0];
	int height = imageData->GetDimensions()[1];

	QImage image(width, height, QImage::Format_RGB32);

	return image;
}

  再提供一个保存QPixmap的版本

QPixmap GetVTKQPixmap(QVTKWidget *qvtkWidget)
{
	vtkSmartPointer<vtkWindowToImageFilter> windowToImageFilter = vtkSmartPointer<vtkWindowToImageFilter>::New();
	windowToImageFilter->SetInput(qvtkWidget->GetRenderWindow());

	#if VTK_MAJOR_VERSION > 8 || (VTK_MAJOR_VERSION == 8 && VTK_MINOR_VERSION >= 1)
		windowToImageFilter->SetScale(1); //image quality
	#else
		windowToImageFilter->SetMagnification(1); //image quality
	#endif

	windowToImageFilter->SetInputBufferTypeToRGBA(); //also record the alpha (transparency) channel
	windowToImageFilter->ReadFrontBufferOff(); // read from the back buffer
	windowToImageFilter->Update();

	vtkImageData* imageData = windowToImageFilter->GetOutput();
	int width = imageData->GetDimensions()[0];
	int height = imageData->GetDimensions()[1];

	QImage image(width, height, QImage::Format_RGB32);
	
	QRgb *rgbPtr = reinterpret_cast<QRgb *>(image.bits()) + width * (height - 1);
	unsigned char *colorsPtr = reinterpret_cast<unsigned char *>(imageData->GetScalarPointer());

	// Loop over the vtkImageData contents.
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++)
		{
			// Swap the vtkImageData RGB values with an equivalent QColor
			*(rgbPtr++) = QColor(colorsPtr[0], colorsPtr[1], colorsPtr[2]).rgb();
			colorsPtr += imageData->GetNumberOfScalarComponents();
		}
		rgbPtr -= width * 2;
	}

	QPixmap pixmap = QPixmap::fromImage(image);
	return pixmap;
}

都需要调用头文件#include

你可能感兴趣的:(学习QT,c++,visual,studio,c语言)