开发者

Writing an IDAT png chunk using C#

I'm trying to create a simple 8-bit png writer, and I've got all the chunks being written correctly except the IDAT chunk (the important one). I believe my problem is in the compression. I've tried using the GZipStream and the DeflateStream classes to output the compressed data to no avail. They don't seem to output the correct format. Are they the wrong approach for this, or should they work correctly?

Here's the method to encode the data that I'm using now:

private byte[] ImageData(Bitmap image, Dictionary<Color, byte> palette) {
    int maxY = image.Height;
    int maxX = image.Width;    开发者_StackOverflow        
    byte[] data = new byte[(maxX + 1) * maxY];
    int idx = 0;
    for (int y = 0; y < maxY; ++y) {
        data[idx++] = 0;    //Filter type 0
        for (int x = 0; x < maxX; ++x) {
            Color c = image.GetPixel(x, y);
            data[idx++] = palette[c];
        }
    }

    MemoryStream stream = new MemoryStream();
    GZipStream compressor = new GZipStream(stream, CompressionMode.Compress);
    compressor.Write(data, 0, data.Length);
    compressor.Flush();
    stream.Flush();
    return stream.ToArray();
}

From what I've read about how the compression method should work (here), is the low-order four bits of the first byte of output should be 1000 to signify compression mode = 8, but with the code above, I get 1110 instead. In fact, based on more rigorous testing, I don't see a two-byte header that is a valid header based on the zlib format until the 1689th byte of the gzipped version of my test data, which I'm fairly certain is not actually the header.

So, will I need to get a zlib library for C# to make this work correctly or is there another way? Like, could I take the output from the GZipStream and convert it easily or something?


Turns out the answer is that you can't use either of those, and you need to use a zlib library instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜