PNGWriter
Repository source: PNGWriter
Question
If you have a question about this example, please use the VTK Discourse Forum
Code¶
PNGWriter.cxx
#include <vtkImageCanvasSource2D.h>
#include <vtkImageCast.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPNGWriter.h>
#include <array>
int main(int argc, char* argv[])
{
std::string outputFilename;
if (argc > 1)
{
outputFilename = argv[1];
}
else
{
outputFilename = "output.png";
}
vtkNew<vtkNamedColors> colors;
std::array<double, 3> drawColor1{0, 0, 0};
std::array<double, 3> drawColor2{0, 0, 0};
auto color1 = colors->GetColor3ub("MediumOrchid").GetData();
auto color2 = colors->GetColor3ub("DarkGreen").GetData();
for (auto i = 0; i < 3; ++i)
{
drawColor1[i] = color1[i];
drawColor2[i] = color2[i];
}
int extent[6] = {0, 99, 0, 99, 0, 0};
vtkNew<vtkImageCanvasSource2D> imageSource;
imageSource->SetExtent(extent);
imageSource->SetScalarTypeToUnsignedChar();
imageSource->SetNumberOfScalarComponents(3);
imageSource->SetDrawColor(drawColor1.data());
imageSource->FillBox(0, 99, 0, 99);
imageSource->SetDrawColor(drawColor2.data());
imageSource->FillBox(40, 70, 20, 50);
imageSource->Update();
vtkNew<vtkImageCast> castFilter;
castFilter->SetOutputScalarTypeToUnsignedChar();
castFilter->SetInputConnection(imageSource->GetOutputPort());
castFilter->Update();
vtkNew<vtkPNGWriter> writer;
writer->SetFileName(outputFilename.c_str());
writer->SetInputConnection(castFilter->GetOutputPort());
writer->Write();
return EXIT_SUCCESS;
}
CMakeLists.txt¶
cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
project(PNGWriter)
find_package(VTK COMPONENTS
CommonColor
CommonCore
IOImage
ImagingCore
ImagingSources
)
if (NOT VTK_FOUND)
message(FATAL_ERROR "PNGWriter: 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(PNGWriter MACOSX_BUNDLE PNGWriter.cxx )
target_link_libraries(PNGWriter PRIVATE ${VTK_LIBRARIES}
)
# vtk_module_autoinit is needed
vtk_module_autoinit(
TARGETS PNGWriter
MODULES ${VTK_LIBRARIES}
)
Download and Build PNGWriter¶
Click here to download PNGWriter and its CMakeLists.txt file. Once the tarball PNGWriter.tar has been downloaded and extracted,
cd PNGWriter/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:
./PNGWriter
WINDOWS USERS
Be sure to add the VTK bin directory to your path. This will resolve the VTK dll's at run time.