Writing a PNG in C++

后端 未结 3 1127
一生所求
一生所求 2020-12-10 22:37

I am trying to write some data to a PNG file using C++ with Visual Studio Express 2013 on Windows 7 64-bit. I understand that to do this, I need to use an external library,

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 23:25

    LodePNG is as easy as you say. I've used it before as well. Just in case you change your mind and decide to encode the data you have into the right format (assuming it is BGRA).. The following will convert the BGRA format to RGBA as required by lodepng..

    std::vector PngBuffer(ImageData.size());
    
    for(std::int32_t I = 0; I < Height; ++I)
    {
        for(std::int32_t J = 0; J < Width; ++J)
        {
            std::size_t OldPos = (Height - I - 1) * (Width * 4) + 4 * J;
            std::size_t NewPos = I * (Width * 4) + 4 * J;
            PngBuffer[NewPos + 0] = ImageData[OldPos + 2]; //B is offset 2
            PngBuffer[NewPos + 1] = ImageData[OldPos + 1]; //G is offset 1
            PngBuffer[NewPos + 2] = ImageData[OldPos + 0]; //R is offset 0
            PngBuffer[NewPos + 3] = ImageData[OldPos + 3]; //A is offset 3
        }
    }
    
    std::vector ImageBuffer;
    lodepng::encode(ImageBuffer, PngBuffer, Width, Height);
    lodepng::save_file(ImageBuffer, "SomeImage.png");
    

提交回复
热议问题