Skip to content

Commit 206ecfb

Browse files
Merge pull request #24 from ukoethe/fix-channels
dump_image(): check if data has a channel axis
2 parents fc71519 + da8593f commit 206ecfb

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

include/xtensor-io/ximage.hpp

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,15 +88,23 @@ namespace xt
8888
{
8989
auto&& ex = eval(data.derived_cast());
9090

91+
XTENSOR_PRECONDITION(ex.dimension() == 2 || ex.dimension() == 3,
92+
"dump_image(): data must have 2 or 3 dimensions (channels must be last).");
93+
9194
OIIO::ImageOutput* out = OIIO::ImageOutput::create(filename);
9295
if (!out)
9396
{
9497
// something went wrong
95-
throw std::runtime_error("Error opening file to write image.");
98+
throw std::runtime_error("dump_image(): Error opening file '" + filename + "' to write image.");
9699
}
100+
101+
int channels = ex.dimension() == 2
102+
? 1
103+
: static_cast<int>(ex.shape()[2]);
104+
97105
OIIO::ImageSpec spec(static_cast<int>(ex.shape()[1]),
98106
static_cast<int>(ex.shape()[0]),
99-
static_cast<int>(ex.shape()[2]), OIIO::TypeDesc::UINT8);
107+
channels, OIIO::TypeDesc::UINT8);
100108

101109
spec.attribute("CompressionQuality", quality);
102110

test/test_ximage.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
#include "gtest/gtest.h"
1010
#include "xtensor/xoperation.hpp"
11+
#include "xtensor/xview.hpp"
1112

1213
#include "xtensor-io/ximage.hpp"
1314

@@ -53,6 +54,12 @@ namespace xt
5354
EXPECT_TRUE(test);
5455
}
5556

57+
TEST(ximage, exceptions)
58+
{
59+
EXPECT_THROW(dump_image("files/dump_test.png", view(test_image_rgb, all(), 0, 0)), std::runtime_error);
60+
EXPECT_THROW(dump_image("files/dump_test.png", view(test_image_rgb, all(), all(), all(), newaxis())), std::runtime_error);
61+
}
62+
5663
TEST(ximage, save_png)
5764
{
5865
dump_image("files/dump_test.png", test_image_rgb);

0 commit comments

Comments
 (0)