Check Color within Bitmap - CSharp System.Drawing

CSharp examples for System.Drawing:Bitmap

Description

Check Color within Bitmap

Demo Code


using System.Drawing.Imaging;
using System.Drawing;
using System;/*from  w w w .  j  a v  a 2 s. com*/

public class Main{
    public static bool Color(Bitmap b, int red, int green, int blue)
      {
         if (red < -255 || red > 255) return false;
         if (green < -255 || green > 255) return false;
         if (blue < -255 || blue > 255) return false;

         // GDI+ still lies to us - the return format is BGR, NOT RGB.
         BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

         int stride = bmData.Stride;
         System.IntPtr Scan0 = bmData.Scan0;

         unsafe
         {
            byte * p = (byte *)(void *)Scan0;

            int nOffset = stride - b.Width*3;
            int nPixel;

            for(int y=0;y<b.Height;++y)
            {
               for(int x=0; x < b.Width; ++x )
               {
                  nPixel = p[2] + red;
                  nPixel = Math.Max(nPixel, 0);
                  p[2] = (byte)Math.Min(255, nPixel);

                  nPixel = p[1] + green;
                  nPixel = Math.Max(nPixel, 0);
                  p[1] = (byte)Math.Min(255, nPixel);

                  nPixel = p[0] + blue;
                  nPixel = Math.Max(nPixel, 0);
                  p[0] = (byte)Math.Min(255, nPixel);

                  p += 3;
               }
               p += nOffset;
            }
         }

         b.UnlockBits(bmData);

         return true;
      }
}

Related Tutorials