【发布时间】:2019-07-25 13:57:33
【问题描述】:
我有一个简单的调试函数,它将字节写入将显示为图像的文件。它遵循ppm 格式。
原来我是这样用的:
static void SaveDebugImage(const std::string& filePath, const unsigned char* psdata, const int resolution)
{
// Debug: print stored data in file
std::ofstream file;
file.open(filePath, std::ios::out | std::ios::binary);
if (!file.is_open())
{
// Throws error and crashes the program on purpose
RError("[ImageDebug::SaveDebugImage] Cannot write to %s", filePath.c_str());
}
file << "P6"
<< "\n"
<< resolution << "\n"
<< resolution << "\n"
<< "255"
<< "\n";
const char zero = 0;
for (int i = 0; i < resolution * resolution; ++i)
{
file.write(reinterpret_cast<const char*>(pxdata), sizeof(*pxdata));
++pxdata;
file.write(reinterpret_cast<const char*>(pxdata), sizeof(*pxdata));
++pxdata;
file.write(&zero, sizeof(zero));
++pxdata;
}
file.flush();
file.close();
}
你可以看到它跳过了颜色的最后一个字节,这是因为数据不是严格的 RGB 图像,而是一种元信息格式。 R、G 和 B 通道的含义不是颜色。您还可以观察到对const char zero = 0 的需求,我必须使用它来写零。
我现在手头有一个真正提供表面颜色的函数,它可能看起来像这样:
OurLibrary::Color getRealColor(byte r, byte g, byte b);
现在假设这个虚构的Color 类有一个unsigned char getR() const 方法,我如何在没有临时变量的情况下将结果写入文件。现在我必须这样做:
OurLibrary::Color pixelColor(getRealColor( ... ));
const unsigned char colorR = pixelColor.getR();
file.write(reinterpret_cast<const char*>(&colorR), sizeof(colorR));
我更喜欢:
file.write(pixelColor.getR());
有没有这样的方法?我在文档中找不到它。
【问题讨论】:
-
仅供参考,我认为在
.close之前调用.flush是多余的? -
getR是按引用还是按值返回?如果它通过引用返回,则直接使用它。 -
@NathanOliver 更新问题,它返回一个值。
-
@Yksisarvinen 不会添加字符串表示吗?我以二进制格式书写 - 每种颜色 1 个字节。
-
最简单的选择是更改
getR以通过引用返回。然后你可以使用file.write(reinterpret_cast<const char*>(&pixelColor.getR()), sizeof(pixelColor.getR()));