Bitmap Brightness - CSharp System.Drawing

CSharp examples for System.Drawing:Image Operation

Description

Bitmap Brightness

Demo Code


using System.Drawing.Imaging;
using System.Drawing;
using System;//from   ww w  . j a v a2 s  . co m

public class Main{
        public static bool Brightness(Bitmap b, int nBrightness)
      {
         if (nBrightness < -255 || nBrightness > 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;

         int nVal = 0;

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

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

            for(int y=0;y<b.Height;++y)
            {
               for(int x=0; x < nWidth; ++x )
               {
                  nVal = (int) (p[0] + nBrightness);
      
                  if (nVal < 0) nVal = 0;
                  if (nVal > 255) nVal = 255;

                  p[0] = (byte)nVal;

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

         b.UnlockBits(bmData);

         return true;
      }
}

Related Tutorials