欢迎访问!
您的支持是我们不断前行的动力!

C# Bitmap转为单色图片

参数 PixelFormat f 为原图的像素格式,如24位色,32位色等…

/// <summary>
/// Bitmap转单色图片
/// </summary>
/// <param name="SrcImg"></param>
/// <returns></returns>
public static Bitmap ConvertBitmapTo1bpp(Bitmap SrcImg, PixelFormat f)
{
    unsafe
    {
        byte* SrcPointer, DestPointer;
        int Width, Height, SrcStride, DestStride;
        int X, Y, Index, Sum; ;
        Bitmap DestImg = new Bitmap(SrcImg.Width, SrcImg.Height, PixelFormat.Format1bppIndexed);
        BitmapData SrcData = new BitmapData();
        SrcImg.LockBits(new Rectangle(0, 0, SrcImg.Width, SrcImg.Height), ImageLockMode.ReadOnly, f, SrcData);
        BitmapData DestData = new BitmapData();
        DestImg.LockBits(new Rectangle(0, 0, SrcImg.Width, SrcImg.Height), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed, DestData);
        Width = SrcImg.Width; Height = SrcImg.Height; SrcStride = SrcData.Stride; DestStride = DestData.Stride;
        for (Y = 0; Y < Height; Y++)
        {
            SrcPointer = (byte*)SrcData.Scan0 + Y * SrcStride;
            DestPointer = (byte*)DestData.Scan0 + Y * DestStride;
            Index = 7; Sum = 0;
            for (X = 0; X < Width; X++)
            {
                if (*SrcPointer + (*(SrcPointer + 1) << 1) + *(SrcPointer + 2) >= 512) Sum += (1 << Index);
                if (Index == 0)
                {
                    *DestPointer = (byte)Sum;
                    Sum = 0;
                    Index = 7;
                    DestPointer++;
                }
                else
                    Index--;
                SrcPointer += 3;
            }
            if (Index != 7) *DestPointer = (byte)Sum;
        }
        SrcImg.UnlockBits(SrcData);
        DestImg.UnlockBits(DestData);
        return DestImg;
    }
}
赞(1) 打赏
转载请注明出处,未注明出处不得转载,蜘蛛侠 » C# Bitmap转为单色图片
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

蜘蛛侠,您身边的爬虫专家!

觉得文章有用就打赏一下文章作者吧

支付宝扫一扫打赏

微信扫一扫打赏