Accord.Imaging.Formats.PNMCodec.ReadHeader C# (CSharp) Method

ReadHeader() private method

private ReadHeader ( Stream stream ) : PNMImageInfo
stream Stream
return PNMImageInfo
        private PNMImageInfo ReadHeader(Stream stream)
        {
            // read magic word
            byte magic1 = (byte)stream.ReadByte();
            byte magic2 = (byte)stream.ReadByte();

            // check if it is valid PNM image
            if ((magic1 != 'P') || (magic2 < '1') || (magic2 > '6'))
            {
                throw new FormatException("The stream does not contain PNM image.");
            }

            // check if it is P5 or P6 format
            if ((magic2 != '5') && (magic2 != '6'))
            {
                throw new NotSupportedException("Format is not supported yet. Only P5 and P6 are supported for now.");
            }

            int width = 0, height = 0, maxValue = 0;

            try
            {
                // read image's width and height
                width = ReadIntegerValue(stream);
                height = ReadIntegerValue(stream);
                // read pixel's highiest value
                maxValue = ReadIntegerValue(stream);
            }
            catch
            {
                throw new ArgumentException("The stream does not contain valid PNM image.");
            }

            // check if all attributes are valid
            if ((width <= 0) || (height <= 0) || (maxValue <= 0))
            {
                throw new ArgumentException("The stream does not contain valid PNM image.");
            }

            // check maximum pixel's value
            if (maxValue > 255)
            {
                throw new NotSupportedException("255 is the maximum pixel's value, which is supported for now.");
            }

            // prepare image information
            PNMImageInfo imageInfo = new PNMImageInfo(width, height, (magic2 == '5') ? 8 : 24, 0, 1);
            imageInfo.Version = (int)(magic2 - '0');
            imageInfo.MaxDataValue = maxValue;

            return imageInfo;
        }