首页  编辑  

Bitmap处理成灰度图象

Tags: /C#/图形图像/   Date Created:

using System . Runtime . InteropServices;

using System . Drawing . Drawing2D;

using System . Drawing . Imaging;

public static bool BitmapGray( Bitmap ABitmap)

{

    if (ABitmap == null ) return false ;

    byte R = 0 , G = 0 , B = 0 ;

    BitmapData vBitmapData = ABitmap . LockBits(

        new Rectangle ( 0 , 0 , ABitmap . Width, ABitmap . Height),

        ImageLockMode . ReadWrite, PixelFormat . Format32bppRgb);

    int vAddress = ( int )vBitmapData . Scan0;

    int vOffset = vBitmapData . Stride - ABitmap . Width * 4 ;

    int h = ABitmap . Height, w = ABitmap . Width;

    for ( int y = 0 ; y < h; y ++ )

   {

        for ( int x = 0 ; x < w; x ++ )

       {

            int i = Marshal . ReadInt32(( IntPtr )vAddress);

           R = ( byte )(i >> 0 & 0xff );

           G = ( byte )(i >> 8 & 0xff );

           B = ( byte )(i >> 16 & 0xff );

           R = ( byte )(( 77 * R + 151 * G + 28 * B) >> 8 );

           i = ( int )(i & 0xff000000 ) | R << 0 | R << 8 | R << 16 ;

            Marshal . WriteInt32(( IntPtr )vAddress, i);

           vAddress += 4 ;

       }

       vAddress += vOffset;

   }

   ABitmap . UnlockBits(vBitmapData);

    return true ;

} /* BitmapGray */