在 C++ 中将一个简单的图像缓冲区保存为 png

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2287757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:54:11  来源:igfitidea点击:

Saving a simple image buffer to png in C++

c++png

提问by henle

I'd like to do this in a platform independant way, and I know libpng is a possibility, but I find it hard to figure out how. Does anyone know how to do this in a simple way?

我想以独立于平台的方式执行此操作,并且我知道 libpng 是一种可能性,但我发现很难弄清楚如何进行。有谁知道如何以简单的方式做到这一点?

采纳答案by Matthieu M.

There is a C++ wrapper for libpngcalled Png++. Check it hereor just google it.

有一个 C++ 包装器用于libpng调用Png++. 在这里检查或只是谷歌它。

They have a real C++ interface with templates and such that uses libpngunder the hood. I've found the code I have written quite expressive and high-level.

他们有一个带有模板的真正的 C++ 接口,并且libpng在幕后使用。我发现我编写的代码非常具有表现力和高级别的。

Example of "generator" which is the heart of the algorithm:

作为算法核心的“生成器”示例:

class PngGenerator : public png::generator< png::gray_pixel_1, PngGenerator>
{
  typedef png::generator< png::gray_pixel_1, PngGenerator> base_t;
public:
  typedef std::vector<char> line_t;
  typedef std::vector<line_t> picture_t;

  PngGenerator(const picture_t& iPicture) :
    base_t(iPicture.front().size(), iPicture.size()),
    _picture(iPicture), _row(iPicture.front().size())
  {
  } // PngGenerator

  png::byte* get_next_row(size_t pos)
  {
    const line_t& aLine = _picture[pos];

    for(size_t i(0), max(aLine.size()); i < max; ++i)
      _row[i] = pixel_t(aLine[i] == Png::White_256);
         // Pixel value can be either 0 or 1
         // 0: Black, 1: White

    return row_traits::get_data(_row);
  } // get_next_row

private:
  // To be transformed
  const picture_t& _picture;

  // Into
  typedef png::gray_pixel_1 pixel_t;
  typedef png::packed_pixel_row< pixel_t > row_t;
  typedef png::row_traits< row_t > row_traits;
  row_t _row; // Buffer
}; // class PngGenerator

And usage is like this:

用法是这样的:

std::ostream& Png::write(std::ostream& out)
{
  PngGenerator aPng(_picture);
  aPng.write(out);
  return out;
}

There were some bits still missing from libpng(interleaving options and such), but frankly I did not use them so it was okay for me.

仍然缺少一些位libpng(交错选项等),但坦率地说,我没有使用它们,所以对我来说没关系。

回答by sbk

I'd say libpng is still the easiest way. There's example read -> process -> write png program, it is fairly simple once you strip the error handling (setjmp/longjmp/png_jmpbuf) stuff. It doesn't get simpler than that.

我会说 libpng 仍然是最简单的方法。有一个例子 read -> process -> write png program,一旦你去掉了错误处理(setjmp/longjmp/png_jmpbuf)的东西,它就相当简单了。没有比这更简单的了。