-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCV2Image.cs
96 lines (88 loc) · 3.59 KB
/
CV2Image.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.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace PaletteEditor
{
class CV2Image
{
private readonly bool _UsePalette;
private Bitmap _Bitmap;
private byte[,] _Index;
public CV2Image(string filename)
{
using (FileStream f_in = File.OpenRead(filename))
{
byte[] header = new byte[1 + 4 + 4 + 4 + 4];
f_in.Read(header, 0, header.Length);
int width = BitConverter.ToInt32(header, 1);
int height = BitConverter.ToInt32(header, 5);
int stride = BitConverter.ToInt32(header, 9);
this._UsePalette = (header[0] == 8);
if (header[0] == 8)
{
this._Index = new byte[height, width];
this._Bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
var data = this._Bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
byte[] readBuffer = new byte[stride];
for (int i = 0; i < height; ++i)
{
f_in.Read(readBuffer, 0, stride);
Marshal.Copy(readBuffer, 0, data.Scan0 + data.Stride * i, width * 1);
Buffer.BlockCopy(readBuffer, 0, _Index, width * i, width);
}
this._Bitmap.UnlockBits(data);
}
else if (header[0] == 16)
{
this._Bitmap = new Bitmap(width, height, PixelFormat.Format16bppArgb1555);
var data = this._Bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format16bppArgb1555);
byte[] readBuffer = new byte[2 * stride];
for (int j = 0; j < height; ++j)
{
f_in.Read(readBuffer, 0, 2 * stride);
Marshal.Copy(readBuffer, 0, data.Scan0 + data.Stride * j, width * 2);
}
this._Bitmap.UnlockBits(data);
}
else if (header[0] == 24 || header[0] == 32)
{
this._Bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
var data = this._Bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
byte[] readBuffer = new byte[4 * stride];
for (int j = 0; j < height; ++j)
{
f_in.Read(readBuffer, 0, 4 * stride);
Marshal.Copy(readBuffer, 0, data.Scan0 + data.Stride * j, width * 4);
}
this._Bitmap.UnlockBits(data);
}
}
}
public void ApplyPalette(Color[] pal)
{
if (_UsePalette && pal != null)
{
var palette = _Bitmap.Palette;
for (int i = 0; i < 256; ++i)
{
palette.Entries[i] = pal[i];
}
_Bitmap.Palette = palette;
}
}
public Bitmap Image { get { return _Bitmap; } }
public byte this[int x, int y]
{
get
{
return _Index == null ? (byte)0 : _Index[y, x];
}
}
}
}