Ptr VS Marshal === ###### tags: `C# Image` 參考資料 http://yy-programer.blogspot.com/2012/08/c.html ![](https://i.imgur.com/DzuYoJZ.png) ```csharp= using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace ImageArray { class Program { public static byte[] RGB2ArrayMarshal(Bitmap srcBitmap) { int width = srcBitmap.Width; int height = srcBitmap.Height; int len​​gth = height * 3 * width; byte[] RGB = new byte[length]; BitmapData data = srcBitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); System.Runtime.InteropServices.Marshal.Copy(data.Scan0, RGB, 0, RGB.Length); srcBitmap.UnlockBits(data); return RGB; } public static byte[] RGB2ArrayPtr(Bitmap srcBitmap) { BitmapData sourceData = srcBitmap.LockBits(new Rectangle(0, 0, srcBitmap.Width, srcBitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); IntPtr source_scan = sourceData.Scan0; int length = srcBitmap.Width * srcBitmap.Height; byte[] RGB = new byte[length]; unsafe { byte* source_p = (byte*)source_scan.ToPointer(); for (int i = 0; i < length; i++) { RGB[i] = (byte)source_p[0]; } /* byte* source_p = (byte*)source_scan.ToPointer(); for (int h = 0; h < srcBitmap.Height; h++) { for (int w = 0; w < sourceData.Width; w++) { source_p[0] = 255; //A source_p++; source_p[0] = 255; //R source_p++; source_p[0] = 155; //G source_p++; source_p[0] = 55; //B source_p++; } } */ } srcBitmap.UnlockBits(sourceData); return RGB; } static void Main(string[] args) { string path = @"C:\Users\Lee\Desktop\FHDImage.bmp"; Bitmap bmp = new Bitmap(path); byte[] array; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < 100; i++) { array = RGB2ArrayMarshal(bmp); } stopwatch.Stop(); Console.WriteLine(string.Format("Marshal x 100 = {0}", stopwatch.ElapsedMilliseconds.ToString())); stopwatch.Reset(); stopwatch.Start(); byte[] array2; for (int i = 0; i<100; i++) { array2 = RGB2ArrayPtr(bmp); } stopwatch.Stop(); Console.WriteLine(string.Format("Ptr x 100 = {0}", stopwatch.ElapsedMilliseconds.ToString())); Console.Read(); } } } ```