.NET ez 2013-02-22
以下有兩種方法複製 BitmapData,一個是使用 unsafe 方法,一個一個 byte 複製,另外一個是複製記憶體區塊,較為快速。
目前測試為,第二種方法比第一種方法快四倍。
using (Bitmap bmp = new Bitmap("檔案路徑")) { BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); Stopwatch sw = new Stopwatch(); sw.Start(); for (int xx = 0; xx < 1000; xx++) { //一個一個byte複製 int dataIndex = 0, height = bmpData.Height, width = bmpData.Width; byte[] data = new byte[width * height * 3]; unsafe { byte* p = (byte*)bmpData.Scan0.ToPointer(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { data[dataIndex++] = p[0]; data[dataIndex++] = p[1]; data[dataIndex++] = p[2]; p += 3; } } } } sw.Stop(); Console.WriteLine("Time1:" + sw.ElapsedMilliseconds.ToString()); sw.Reset(); sw.Start(); for (int xx = 0; xx < 1000; xx++) { byte[] data = new byte[bmpData.Width * bmpData.Height * 3]; Marshal.Copy(bmpData.Scan0, data, 0, data.Length); //複製記憶體區塊 } sw.Stop(); Console.WriteLine("Time2:" + sw.ElapsedMilliseconds.ToString()); bmp.UnlockBits(bmpData); }
標籤: .NET
本文章網址:
https://www.ez2o.com/Blog/Post/csharp-BitmapData-to-Byte-Array
https://www.ez2o.com/Blog/Post/332
https://www.ez2o.com/Blog/Post/csharp-BitmapData-to-Byte-Array
https://www.ez2o.com/Blog/Post/332