本文介绍了从两个二维数组创建位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示灰度图像的二维double[,] rawImage数组,该数组中的每个元素的合理值都在0〜1之间,我需要要将其转换为Bitmap图片,我使用了以下代码:

I've a two-dimensional double[,] rawImage array representing a gray level image with each element in the array has a rational value from 0 ~ 1 , and I needto convert it to Bitmap image, I've used the following code:

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数据类型的指针来完成上述工作.

but it seems to be so slow.I don't know if there is a way to do the above work using pointers of short data type.

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

How can I write a faster code using pointers to handle this function ?

推荐答案

这对您来说应该足够了.该示例是根据以下源代码编写的.

This should be enough for you. The example is written according to this 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);
    }
}

这篇关于从两个二维数组创建位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:00