public static Image ReadPnm(Stream inputStream) { char ch; string str; string magicWord = ((char)inputStream.ReadByte()).ToString() + ((char)inputStream.ReadByte()).ToString(); inputStream.ReadByte(); PnmEncoding pNMEncoding = PnmFactory.GetPNMEncoding(magicWord); IPnmDataReader iPNMDataReader = PnmFactory.GetIPNMDataReader(inputStream, pNMEncoding); if (iPNMDataReader == null) { throw new Exception("Currently only Binary and ASCII encoding is supported"); } IPnmReader iPNMReader = PnmFactory.GetIPNMReader(PnmFactory.GetPNMType(magicWord)); if (iPNMReader == null) { throw new Exception("Currently only PBM, PGM and PNM Image Types are supported"); } do { str = iPNMDataReader.ReadLine(); if (str.Length == 0) { ch = '#'; } else { ch = str.Substring(0, 1).ToCharArray(0, 1)[0]; } }while (ch == '#'); string[] strArray = str.Split(new char[] { ' ' }); int width = int.Parse(strArray[0]); int height = int.Parse(strArray[1]); if (magicWord != "P1") { do { str = iPNMDataReader.ReadLine(); if (str.Length == 0) { ch = '#'; } else { ch = str.Substring(0, 1).ToCharArray(0, 1)[0]; } }while (ch == '#'); if (int.Parse(str) != 0xff) { Console.WriteLine("Warning, max value for pixels in this image is not 255"); } } return(iPNMReader.ReadImageData(iPNMDataReader, width, height)); }
public static void WritePnm(Stream fs, Image im, PnmEncoding encoding, PnmType ptype) { IPnmDataWriter iPNMDataWriter = PnmFactory.GetIPNMDataWriter(fs, encoding); if (iPNMDataWriter == null) { throw new Exception("Currently only Binary and ASCII encoding is supported"); } try { iPNMDataWriter.WriteLine(PnmFactory.GetMagicWord(ptype, encoding)); iPNMDataWriter.WriteLine(im.Width.ToString() + " " + im.Height.ToString()); if (ptype != PnmType.Pbm) { iPNMDataWriter.WriteLine("255"); } PnmFactory.GetIPNMWriter(ptype).WriteImageData(iPNMDataWriter, im); } catch { throw; } }