Example #1
0
        public void Write(Texture2D texture2D, Stream outputStream)
        {
            width  = texture2D.Width;
            height = texture2D.Height;

            GetColorData(texture2D);

            // write PNG signature
            outputStream.Write(HeaderChunk.PngSignature, 0, HeaderChunk.PngSignature.Length);

            // write header chunk
            var headerChunk = new HeaderChunk();

            headerChunk.Width             = (uint)texture2D.Width;
            headerChunk.Height            = (uint)texture2D.Height;
            headerChunk.BitDepth          = 8;
            headerChunk.ColorType         = colorType;
            headerChunk.CompressionMethod = 0;
            headerChunk.FilterMethod      = 0;
            headerChunk.InterlaceMethod   = 0;

            var headerChunkBytes = headerChunk.Encode();

            outputStream.Write(headerChunkBytes, 0, headerChunkBytes.Length);

            // write data chunks
            var encodedPixelData    = EncodePixelData(texture2D);
            var compressedPixelData = new MemoryStream();

            ZlibStream deflateStream = null;

            try
            {
                deflateStream = new ZlibStream(compressedPixelData, CompressionMode.Compress);
                deflateStream.Write(encodedPixelData, 0, encodedPixelData.Length);
                deflateStream.Finish();
            }
            catch (Exception exception)
            {
                throw new Exception("An error occurred during DEFLATE compression.", exception);
            }

            var dataChunk = new DataChunk();

            dataChunk.Data = compressedPixelData.ToArray();
            var dataChunkBytes = dataChunk.Encode();

            outputStream.Write(dataChunkBytes, 0, dataChunkBytes.Length);

            deflateStream.Dispose();
            compressedPixelData.Dispose();

            // write end chunk
            var endChunk      = new EndChunk();
            var endChunkBytes = endChunk.Encode();

            outputStream.Write(endChunkBytes, 0, endChunkBytes.Length);
        }