/// <summary> /// Get the color data in the region of rectangle /// </summary> /// <param name="bitmap">The picture you wang to get color from</param> /// <param name="rect">The region that will be calculated</param> /// <returns></returns> private imgdata getData(Bitmap bitmap, Rectangle rect) { BitmapData data = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int nbyte = data.Width * data.Height; imgdata d = new imgdata(nbyte); int index = 0; int offset = data.Stride - bitmap.Width * 3 + rect.Left * 3 + rect.Right * 3; unsafe { byte *ptr = (byte *)(void *)data.Scan0; for (int i = 0; i < data.Height; i++) { for (int j = 0; j < data.Width; j++) { d.b[index] = *ptr; ptr++; d.g[index] = *ptr; ptr++; d.r[index] = *ptr; ptr++; index++; } ptr += offset; } } bitmap.UnlockBits(data); return(d); }
/// <summary> /// Get the average color in the region of rectangle /// </summary> /// <param name="bitmap">The picture you wang to get color from</param> /// <param name="rect">The region that will be calculated</param> /// <returns></returns> public Color getAverage(Bitmap bitmap, Rectangle r) { imgdata d = getData(bitmap, r); int bs = 0, gs = 0, rs = 0; for (int i = 0; i < d.index; i++) { bs += d.b[i]; gs += d.g[i]; rs += d.r[i]; } return(Color.FromArgb(rs / d.index, gs / d.index, rs / d.index)); }