public static void WritePNM(string FilePath, System.Drawing.Image im, PNMEncoding encoding, PNMType ptype) { FileStream fs = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None); IPNMDataWriter dw = PNMFactory.GetIPNMDataWriter(fs, encoding); if (dw == null) { throw new Exception ("Currently only Binary and ASCII encoding is supported"); } try { //write image header dw.WriteLine(PNMFactory.GetMagicWord(ptype, encoding)); dw.WriteLine(im.Width.ToString() + " " + im.Height.ToString()); if (ptype != PNMType.PBM) { dw.WriteLine("255"); } IPNMWriter imWriter = PNMFactory.GetIPNMWriter(ptype); imWriter.WriteImageData(dw, im); } catch { throw; } }
public void WriteImageData(IPNMDataWriter dw, System.Drawing.Image im) { int i = 0; //convert im to grey scale and write to output file for (int y = 0; y < im.Height; y++) { for (int x = 0; x < im.Width; x++) { Color c = ((Bitmap)im).GetPixel(x, y); int luma = (int)(c.R + c.G + c.B); if (luma > 0) { dw.WriteByte((byte)1); } else { dw.WriteByte((byte)0); } i++; //one line cannot contain more than 70 chars if (i >= 34) { i = 0; dw.WriteLine(string.Empty); } } } dw.Close(); }