更新
以爲我會改進這個帖子以供將來參考。
如果將像素數據存儲爲32位整數(理想情況下無符號數組),則更容易。每個整數的4個字節應分別對應於alpha,紅色,綠色和藍色通道。如果您不使用Alpha通道,請將其保持爲空。
public void SetPixel(int x, int y, uint colour) => pixels[x + y * width] = colour;
由於starbeamrainbowlabs指出:
GCHandle
,Bitmap
,並PixelFormat
在System.Runtime.InteropServices
發現,System.Drawing
// If your image is always going to be the same size, make these constant -
// it speeds things up tremendously.
var width = 640;
var height = 480;
// Create the array to contain bitmap's pixel data.
// Making the pixels unsigned *can* speed up certain arithmetic operations,
// so use them if you're going to be manipulating colours as integers in the array.
// Note that array size is width * height only.
var pixels = new uint[width * height];
/* <Perform array operations here> */
// Create a handle to the object on the heap.
// Making it 'Pinned' prevents the GC from moving it around in memory.
var gchPixels = GCHandle.Alloc(pixels, GCHandleType.Pinned);
// Create the bitmap itself.
// Note: if you plan on making use of the alpha channel, make sure you use
// Format32bppArgb instead (no P).
// Format32bppPArgb means that the alpha channel is present but should be ignored.
var bitmap = new Bitmap(width, height, width * sizeof(uint),
PixelFormat.Format32bppPArgb,
gchPixels.AddrOfPinnedObject());
/* <Perform bitmap operations here> */
// Free the handle to stop the GC from pinning the array.
// This is important if you were dealing with a large array.
gchPixels.Free();
您可以在某個座標設定像素創建你自己的方法,和System.Drawing.Imaging
。
原來的答案下面
有這樣做的相當的好方法,但它需要你使用數組或字節,而不是一個列表。如果你想改變這是ARGB,只需更改的 '3' 所有實例 '4', 和使用PixelFormat.Format32bppArgb
// Define the width and the height of the image
int width = 100,
height = 100;
/* Create an array of bytes consisting of the area's worth of pixels
* with 3 bytes of data each.
*/
byte[] pixels = new byte[width * height * 3];
/* > Code for making the image etc. here < */
// Create our bitmap.
/* GCHandle requires System.Runtime.InteropServices
* PixelFormat requires System.Drawing.Imaging.
*/
Bitmap bmp = new Bitmap(width, height, width * 3, PixelFormat.Format24bppRgb,
GCHandle.Alloc(pixels, GCHandleType.Pinned).AddrOfPinnedObject());
:
考慮這一點。
正如我所說的,這需要你使用一個數組而不是一個列表,但這個 應該不會太困難,只要你知道圖像的寬度和高度。 數組中設置一個單獨的像素(也許會讓一個方法 本)的一個好辦法:
pixels[x + y * width] = R;
pixels[x + y * width + 1] = G;
pixels[x + y * width + 2] = B;
這種方法一般是相當快過,如果這是在所有必要的不管你是 做。
來源:經驗。
爲什麼你使用ArrayList存儲像素數據? – 2013-04-21 10:36:17
我正在聚集圖像,所以我不知道從開始的圖像集羣的確切大小,如果我在大型數據集上運行一次循環,它需要很多時間..所以我使用數組列表進行動態分配 – greatmajestics 2013-04-21 10:37:13
什麼是您的項目類型? 'WPF','Windows Form',... – 2013-04-21 10:39:46