diff --git a/include/xtensor-io/ximage.hpp b/include/xtensor-io/ximage.hpp index 8f51127..d8025ad 100644 --- a/include/xtensor-io/ximage.hpp +++ b/include/xtensor-io/ximage.hpp @@ -88,15 +88,23 @@ namespace xt { auto&& ex = eval(data.derived_cast()); + XTENSOR_PRECONDITION(ex.dimension() == 2 || ex.dimension() == 3, + "dump_image(): data must have 2 or 3 dimensions (channels must be last)."); + OIIO::ImageOutput* out = OIIO::ImageOutput::create(filename); if (!out) { // something went wrong - throw std::runtime_error("Error opening file to write image."); + throw std::runtime_error("dump_image(): Error opening file '" + filename + "' to write image."); } + + int channels = ex.dimension() == 2 + ? 1 + : static_cast(ex.shape()[2]); + OIIO::ImageSpec spec(static_cast(ex.shape()[1]), static_cast(ex.shape()[0]), - static_cast(ex.shape()[2]), OIIO::TypeDesc::UINT8); + channels, OIIO::TypeDesc::UINT8); spec.attribute("CompressionQuality", quality); diff --git a/test/test_ximage.cpp b/test/test_ximage.cpp index 6031bfd..4bdb1b8 100644 --- a/test/test_ximage.cpp +++ b/test/test_ximage.cpp @@ -8,6 +8,7 @@ #include "gtest/gtest.h" #include "xtensor/xoperation.hpp" +#include "xtensor/xview.hpp" #include "xtensor-io/ximage.hpp" @@ -53,6 +54,12 @@ namespace xt EXPECT_TRUE(test); } + TEST(ximage, exceptions) + { + EXPECT_THROW(dump_image("files/dump_test.png", view(test_image_rgb, all(), 0, 0)), std::runtime_error); + EXPECT_THROW(dump_image("files/dump_test.png", view(test_image_rgb, all(), all(), all(), newaxis())), std::runtime_error); + } + TEST(ximage, save_png) { dump_image("files/dump_test.png", test_image_rgb);