/
PGMUtil.cs
96 lines (89 loc) · 3.59 KB
/
PGMUtil.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace WindowsFormsApplication1
{
public static class PGMUtil
{
private static ColorPalette grayScale;
public static Bitmap ToBitmap(string filePath)
{
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
using (BinaryReader reader = new BinaryReader(fs, Encoding.ASCII))
{
if (reader.ReadChar() == 'P' && reader.ReadChar() == '5')
{
reader.ReadChar();
//reader.ReadBytes(24);
int width = 0;
int height = 0;
int level = 0;
bool two = false;
StringBuilder sb = new StringBuilder();
width = ReadNumber(reader, sb);
height = ReadNumber(reader, sb);
level = ReadNumber(reader, sb);
two = (level > 255);
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
if (grayScale == null)
{
grayScale = bmp.Palette;
for (int i = 0; i < 256; i++)
{
grayScale.Entries[i] = Color.FromArgb(i, i, i);
}
}
bmp.Palette = grayScale;
BitmapData dt = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
int offset = dt.Stride - dt.Width;
unsafe
{
byte* ptr = (byte*)dt.Scan0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
byte v;
if (two)
{
v = (byte)(((double)((reader.ReadByte() << 8) + reader.ReadByte()) / level) * 255.0);
}
else
{
v = reader.ReadByte();
}
*ptr = v;
ptr++;
}
ptr += offset;
}
}
bmp.UnlockBits(dt);
return bmp;
}
else
{
throw new InvalidOperationException("target file is not a PGM file");
}
}
}
}
public static void SaveAsBitmap(string src, string dest)
{
ToBitmap(src).Save(dest, ImageFormat.Bmp);
}
private static int ReadNumber(BinaryReader reader, StringBuilder sb)
{
char c = '\0';
sb.Length = 0;
while (Char.IsDigit(c = reader.ReadChar()))
{
sb.Append(c);
}
return int.Parse(sb.ToString());
}
}
}