快乐的果栋

C#/Asp.net/WinForm
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C# 获取图片指定颜色矩形区域

Posted on 2009-05-27 16:05  Create  阅读(2561)  评论(0)    收藏  举报
 /// <summary>
        /// 获取图片指定颜色矩形区域
        /// </summary>
        /// <param name="sourceImage">图片</param>
        /// <param name="targetColor">指定颜色</param>
        /// <returns>矩形区域</returns>
        private Rectangle GetColorRect(Bitmap sourceImage, Color targetColor)
        {
            Rectangle resultRect = new Rectangle(0, 0, 0, 0);
            int left;
            int top;
            int right;
            int bottom;
            if (sourceImage != null && sourceImage.Width > 0 && sourceImage.Height > 0)
            {
                left = sourceImage.Width;
                top = sourceImage.Height;
                right = 0;
                bottom = 0;

                Color color = Color.Black;
                for (int width = 0; width < sourceImage.Width; width++)
                {
                    for (int height = 0; height < sourceImage.Height; height++)
                    {
                        color = sourceImage.GetPixel(width, height);
                        if (color.A == targetColor.A &&
                            color.B==targetColor.B &&
                            color.G==targetColor.G &&
                            color.R==targetColor.R)
                        {
                            if (width < left)
                            {
                                left = width;
                            }
                            if (height < top)
                            {
                                top = height;
                            }
                            if (width > right)
                            {
                                right = width;
                            }
                            if (height > bottom)
                            {
                                bottom = height;
                            }
                        }
                    }
                }
                resultRect = new Rectangle(left, top, right - left, bottom - top);
            }

            return resultRect;
        }