.NET ez 2012-06-20
上一次利用了 GetPixel 及 SetPixel,將圖片轉為灰階,雖然可以達成效果但是效能不佳!
這次採用 BitmapData 並且使用 指標 進行處理,達到更高的處理效率。
using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; namespace Test { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string Photo_route = Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Tulips.jpg"); Bitmap b = (Bitmap)Bitmap.FromFile(Photo_route); pictureBox2.Image = (Bitmap)Bitmap.FromFile(Photo_route); Stopwatch sw = new Stopwatch(); sw.Start(); BitmapData bData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); //使用unsafe允許使用指標 unsafe { byte* p = (byte*)bData.Scan0.ToPointer(); for (int y = 0; y < b.Height; y++) { for (int x = 0; x < b.Width; x++) { byte newColor = (byte)((float)(p[0] + p[1] + p[2]) / 3.0f); p[0] = p[1] = p[2] = newColor; //三個byte組成一個Pixel p += 3; } } b.UnlockBits(bData); } sw.Stop(); pictureBox1.Image = b; MessageBox.Show(sw.ElapsedMilliseconds.ToString() + " /ms"); } } }
unsafe開啟方法:
標籤: .NET
本文章網址:
https://www.ez2o.com/Blog/Post/csharp-Image-Gray-BitmapData
https://www.ez2o.com/Blog/Post/79
https://www.ez2o.com/Blog/Post/csharp-Image-Gray-BitmapData
https://www.ez2o.com/Blog/Post/79