c# - 从双二维数组创建位图

标签 c# arrays image pointers bitmap

我有一个二维 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 数据类型的指针来完成上述工作。

如何使用指针编写更快的代码来处理此函数?

最佳答案

这对你来说应该足够了。例子是根据这个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);
    }
}

关于c# - 从双二维数组创建位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13511661/

相关文章:

c# - 部分 BindingList 到字符串数组

PHP/SQL : ORDER BY or sort($array)?

javascript - 如何加载多个文件图像作为数据 url 并在之后单独更改它们

c# - .NET 编码与字符集的关系

c - 作为参数传递时数组发生变化

c# - 将数据点转换为像素坐标以进行绘图

css - 将文本与图像对齐 - React Native

python - 计算图像中矩形的数量

c# - 并发读取/写入 Redis 集 - 单服务器多客户端

c# - 在 View 模型中实现 IDataErrorInfo