繁体   English   中英

从双二维数组创建位图

[英]Create Bitmap from double two dimentional array

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

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

这对你来说应该足够了。 该示例是根据此源代码编写的

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM