// Load P2 PGM image (grayscale PNM image with ascii encoding)
private static unsafe Bitmap ReadP2Image(TextReader stream, int width, int height, int maxValue)
{
double scalingFactor = 255 / (double)maxValue;
// create new bitmap and lock it
Bitmap image = Tools.CreateGrayscaleImage(width, height);
BitmapData imageData = image.LockBits(ImageLockMode.WriteOnly);
int stride = imageData.Stride;
byte *ptr = (byte *)imageData.Scan0.ToPointer();
int offset = imageData.Stride - imageData.Width;
// load all rows
string all = stream.ReadToEnd();
string[] values = all.Split(emptyChars, StringSplitOptions.RemoveEmptyEntries);
for (int y = 0, z = 0; y < height; y++)
{
// fill next image row
for (int x = 0; x < width; x++, ptr++, z++)
{
*ptr = (byte)(scalingFactor * Byte.Parse(values[z]));
}
ptr += offset;
}
// unlock image and return it
image.UnlockBits(imageData);
return(image);
}