public void EncodeImage(Bitmap inp, Stream outs, float quality = 100.0f) { if (inp == null || outs == null) { return; } int width = inp.Width; int height = inp.Height; if (width < 1 || height < 1) { return; } // !!!{{ TODO: add the encoding code here using (DeflateStream ds = new BufferedDeflateStream(16384, outs, CompressionMode.Compress, true)) { // file header: [ MAGIC, width, height ] ds.WriteByte((byte)((MAGIC >> 24) & 0xff)); ds.WriteByte((byte)((MAGIC >> 16) & 0xff)); ds.WriteByte((byte)((MAGIC >> 8) & 0xff)); ds.WriteByte((byte)(MAGIC & 0xff)); ds.WriteByte((byte)((width >> 8) & 0xff)); ds.WriteByte((byte)(width & 0xff)); ds.WriteByte((byte)((height >> 8) & 0xff)); ds.WriteByte((byte)(height & 0xff)); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { Color col = inp.GetPixel(x, y); int gr = Draw.RgbToGray(col.R, col.G, col.B); ds.WriteByte((byte)(gr & 0xff)); } } } // !!!}} }
public void EncodeImage(Bitmap inp, Stream outs) { if (inp == null || outs == null) { return; } int width = inp.Width; int height = inp.Height; if (width < 1 || height < 1) { return; } // !!!{{ TODO: add the encoding code here DeflateStream ds = new BufferedDeflateStream(16384, outs, CompressionMode.Compress, true); // file header: [ MAGIC, width, height ] ds.WriteByte((byte)((MAGIC >> 24) & 0xff)); ds.WriteByte((byte)((MAGIC >> 16) & 0xff)); ds.WriteByte((byte)((MAGIC >> 8) & 0xff)); ds.WriteByte((byte)(MAGIC & 0xff)); ds.WriteByte((byte)((width >> 8) & 0xff)); ds.WriteByte((byte)(width & 0xff)); ds.WriteByte((byte)((height >> 8) & 0xff)); ds.WriteByte((byte)(height & 0xff)); int buffer = 0; int bufLen = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int gr = (inp.GetPixel(x, y).GetBrightness() < 0.5f) ? 0 : 1; buffer += buffer + gr; if (++bufLen == 8) { ds.WriteByte((byte)(buffer & 0xff)); buffer = 0; bufLen = 0; } } // end of scanline if (bufLen > 0) { buffer <<= 8 - bufLen; ds.WriteByte((byte)(buffer & 0xff)); buffer = 0; bufLen = 0; } } ds.Close(); // !!!}} }