经过前面的讨论,我对Image类进行了优化,代码如下:
//C#灰度图像处理类,作者:wmesci
//http://http://blog.csdn.net/wmesci
unsafe class Image :CriticalHandle, IDisposable
{
[DllImport("kernel32.dll")]
static extern IntPtr LocalAlloc(int flags, int size);
[DllImport("kernel32.dll")]
static extern IntPtr LocalFree(IntPtr memBlock);
[DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")]
static extern unsafe void CopyMemory(void* dst, void* src, int count);
[DllImport("ntdll.dll")]
static extern unsafe void* memset(void* src, byte value, uint size);
const byte Max = 255;
const byte Min = 0;
public Image(int width, int height)
: base(IntPtr.Zero)
{
if (width <= 0 || height <= 0)
throw new ArgumentOutOfRangeException();
Width = width;
Height = height;
Stride = (width + 3) & ~3;
Length = Stride * Height;
base.SetHandle(LocalAlloc(0x40, Length));
Pointer = (byte*)handle.ToPointer();
}
public Image(int width, int height, byte* data)
: this(width, height)
{
SetData(data);
}
public void GetData(void* dst)
{
CopyMemory(dst, Pointer, Length);
}
public void SetData(void* src)
{
CopyMemory(Pointer, src, Length);
}
public readonly int Width;
public readonly int Height;
public readonly int Length;
public readonly int Stride;
public readonly byte* Pointer;
public byte this[int x, int y]
{
get
{
return *(Pointer + y * Stride + x);
}
set
{
*(Pointer + y * Stride + x) = value;
}
}
public Image Clone()
{
return new Image(Width, Height, Pointer);
}
public void Add(Image img)
{
Action<int> act = y =>
{
byte* p1 = Pointer + y * Stride, p2 = (byte*)img.Pointer + y * img.Stride;
for (int x = 0; x < Stride; x += 4, p1 += 4, p2 += 4)
{
int d = (int)p1[0] + (int)p2[0];
if (d < 0)
p1[0] = 0;
else if (d > 255)
p1[0] = 255;
else
p1[0] = (byte)d;
d = (int)p1[1] + (int)p2[1];
if (d < 0)
p1[1] = 0;
else if (d > 255)
p1[1] = 255;
else
p1[1] = (byte)d;
d = (int)p1[2] + (int)p2[2];
if (d < 0)
p1[2] = 0;
else if (d > 255)
p1[2] = 255;
else
p1[2] &#