2011-02-25 157 views

回答

11

這裏是做的非常快,雖然不安全,道:

[編輯]這個例子了0.035毫秒

// Create 2D array of integers 
int width = 320; 
int height = 240; 
int stride = width * 4; 
int[,] integers = new int[width,height]; 

// Fill array with random values 
Random random = new Random(); 
for (int x = 0; x < width; ++x) 
{ 
    for (int y = 0; y < height; ++y) 
    { 
     byte[] bgra = new byte[] { (byte)random.Next(255), (byte)random.Next(255), (byte)random.Next(255), 255 }; 
     integers[x, y] = BitConverter.ToInt32(bgra, 0); 
    } 
} 

// Copy into bitmap 
Bitmap bitmap; 
unsafe 
{ 
    fixed (int* intPtr = &integers[0,0]) 
    { 
     bitmap = new Bitmap(width, height, stride, PixelFormat.Format32bppRgb, new IntPtr(intPtr)); 
    } 
} 

和結果:

result

+0

很好的例子,但圖像看起來不是隨機:) – Pedery 2011-02-25 06:57:50

+0

:)你是對的,我也看到它...因爲C#「隨機」類是基於一個明確的數學算法,我猜它不應該是全部那令人驚訝。 – tbridge 2011-02-25 07:38:35

+0

很好的例子,但是這顯示了一個1維數組,而不是2-D。 – Kohanz 2014-04-25 16:11:39

0

如果有需要速度看my Kinect sample。基本上它創建一個內存區域,並使用一個不安全的指針向內存生成一個Int32數組。 BitmapSource對象用於將位圖(圖像)直接映射到同一區域。這個特殊的例子也使用非託管內存使其與P/Invoke兼容。

This blogpost描述了使用不安全的性能差異。從 部分看看:

注意,您可以一樣好做的Int32 [] - 指針,而不是它使用的例子字節[] - 指針。

0

如果速度是不是一個問題 - 位圖+ SetPixel比保存到一個文件:​​

+0

簡單,但正如你所說:慢。令人驚訝的慢! :) – 2011-02-25 05:37:32

0

Bitmap.LockBits應該工作,如果你想要一個WinForms圖像。

+0

@ozcanovunc:語法已經很完美了。你可能想閱讀關於現在的進行時態。 – 2016-05-19 15:10:45

0

將數組投影到base64字符串中以便流入Bitmap也會變慢嗎?

相關問題