我有一个二维double[,] rawImage
数组,代表一个灰度图像,数组中的每个元素都有一个0~1的理性值,我需要
要将其转换为Bitmap
图片,我使用了以下代码:
private Bitmap ToBitmap(double[,] rawImage)
{
int width = rawImage.GetLength(1);
int height = rawImage.GetLength(0);
Bitmap Image= new Bitmap(width, height);
for (int i = 0; i < height; i++)
for (int j = 0; j < YSize; j++)
{
double color = rawImage[j, i];
int rgb = color * 255;
Image.SetPixel(i, j, rgb , rgb , rgb);
}
return Image;
}
但似乎太慢了。
我不知道是否有办法使用short
数据类型的指针进行上述工作。
如何使用指针编写更快的代码来处理此函数?
答案 0 :(得分:6)
这对你来说应该足够了。该示例是根据此source code编写的。
private unsafe Bitmap ToBitmap(double[,] rawImage)
{
int width = rawImage.GetLength(1);
int height = rawImage.GetLength(0);
Bitmap Image = new Bitmap(width, height);
BitmapData bitmapData = Image.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadWrite,
PixelFormat.Format32bppArgb
);
ColorARGB* startingPosition = (ColorARGB*) bitmapData.Scan0;
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
{
double color = rawImage[i, j];
byte rgb = (byte)(color * 255);
ColorARGB* position = startingPosition + j + i * width;
position->A = 255;
position->R = rgb;
position->G = rgb;
position->B = rgb;
}
Image.UnlockBits(bitmapData);
return Image;
}
public struct ColorARGB
{
public byte B;
public byte G;
public byte R;
public byte A;
public ColorARGB(Color color)
{
A = color.A;
R = color.R;
G = color.G;
B = color.B;
}
public ColorARGB(byte a, byte r, byte g, byte b)
{
A = a;
R = r;
G = g;
B = b;
}
public Color ToColor()
{
return Color.FromArgb(A, R, G, B);
}
}