Creates an 8-bit grayscale bitmap with the contents of the supplied bitmap's specified channel - CSharp System.Drawing

CSharp examples for System.Drawing:Bitmap

Description

Creates an 8-bit grayscale bitmap with the contents of the supplied bitmap's specified channel

Demo Code


using System.Drawing.Imaging;
using System.Drawing;
using System.Collections;
using System;/* w ww.ja  v a 2 s . com*/

public class Main{
    /// <summary>
      /// Creates an 8-bit grayscale bitmap with the contents of the supplied bitmap's specified channel
      /// </summary>
      /// <param name="bmp"></param>
      /// <param name="channel"></param>
      /// <returns></returns>
      public static Bitmap ExtractChannel(Bitmap bmpSrc, int channel)
      {
         Bitmap bmpDst = new Bitmap(bmpSrc.Width, bmpSrc.Height,
            System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
         //ColorPalette pal = bmpDst.Palette;
         //bmpDst.Palette = pal; //System.Drawing.Imaging.PaletteFlags.GrayScale;

         System.Drawing.Imaging.BitmapData dataSrc = bmpSrc.LockBits(new Rectangle(new Point(0,0), bmpSrc.Size),
            System.Drawing.Imaging.ImageLockMode.ReadOnly, bmpSrc.PixelFormat);

         System.Drawing.Imaging.BitmapData dataDst = bmpDst.LockBits(new Rectangle(new Point(0,0), bmpSrc.Size),
            System.Drawing.Imaging.ImageLockMode.WriteOnly, bmpDst.PixelFormat);

         int nBytesPerPix = GetBytesPerPixel(bmpSrc);
         unsafe
         {
            int nWidthSrc = bmpSrc.Width*nBytesPerPix;
            byte* ptrSrc = ((byte*)dataSrc.Scan0) + channel;
            byte* ptrDst = ((byte*)dataDst.Scan0);
            for (int y=0; y<bmpSrc.Height; y++)
            {
               for (int x=0; x<bmpSrc.Width; x++)
               {
                  *ptrDst = *ptrSrc;
                  ptrSrc+=nBytesPerPix;
                  ptrDst++;
               }
               ptrSrc+=dataSrc.Stride-nWidthSrc;
               ptrDst+=dataDst.Stride-bmpDst.Width;
            }
         }
         bmpSrc.UnlockBits(dataSrc);
         bmpDst.UnlockBits(dataDst);

         return bmpDst;
      }
    public static int GetBytesPerPixel(Bitmap bmp)
      {
         //TODO: 16-bit, eg PixelFormat.Format16bppArgb1555
         return (bmp.PixelFormat == PixelFormat.Format24bppRgb)?3:
            ((bmp.PixelFormat == PixelFormat.Format8bppIndexed)?1:4);
      }
}

Related Tutorials