ImageExport
vtk-examples/Cxx/Images/ImageExport
Question
If you have a question about this example, please use the VTK Discourse Forum
Code¶
ImageExport.cxx
#include <vtkImageData.h>
#include <vtkImageExport.h>
#include <vtkNew.h>
#include <memory>
int main(int, char*[])
{
// Create an image data
vtkNew<vtkImageData> imageData;
// Specify the size of the image data
constexpr int dims[3] = {2, 3, 1};
imageData->SetDimensions(dims[0], dims[1], dims[2]);
imageData->AllocateScalars(VTK_UNSIGNED_CHAR, 1);
unsigned char value = 0;
for (int row = 0; row < dims[0]; ++row)
{
for (int col = 0; col < dims[1]; ++col)
{
unsigned char* pixel =
static_cast<unsigned char*>(imageData->GetScalarPointer(row, col, 0));
pixel[0] = value;
value += 10;
}
}
// Create the c-style image to convert the VTK image to
std::unique_ptr<unsigned char> cImage(
new unsigned char[dims[0] * dims[1] * dims[2]]);
vtkNew<vtkImageExport> exporter;
exporter->SetInputData(imageData);
exporter->ImageLowerLeftOn();
exporter->Export(cImage.get());
exporter->Update();
// Output the raw c-style image
for (int row = 0; row < dims[0]; ++row)
{
for (int col = 0; col < dims[1]; ++col)
{
std::cout << static_cast<int>(cImage.get()[col * dims[0] + row]) << " ";
}
std::cout << std::endl;
}
return EXIT_SUCCESS;
}
CMakeLists.txt¶
cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
project(ImageExport)
find_package(VTK COMPONENTS
)
if (NOT VTK_FOUND)
message(FATAL_ERROR "ImageExport: Unable to find the VTK build folder.")
endif()
# Prevent a "command line is too long" failure in Windows.
set(CMAKE_NINJA_FORCE_RESPONSE_FILE "ON" CACHE BOOL "Force Ninja to use response files.")
add_executable(ImageExport MACOSX_BUNDLE ImageExport.cxx )
target_link_libraries(ImageExport PRIVATE ${VTK_LIBRARIES}
)
# vtk_module_autoinit is needed
vtk_module_autoinit(
TARGETS ImageExport
MODULES ${VTK_LIBRARIES}
)
Download and Build ImageExport¶
Click here to download ImageExport and its CMakeLists.txt file. Once the tarball ImageExport.tar has been downloaded and extracted,
cd ImageExport/build
If VTK is installed:
cmake ..
If VTK is not installed but compiled on your system, you will need to specify the path to your VTK build:
cmake -DVTK_DIR:PATH=/home/me/vtk_build ..
Build the project:
make
and run it:
./ImageExport
WINDOWS USERS
Be sure to add the VTK bin directory to your path. This will resolve the VTK dll's at run time.