bitmap图像转byte数组(c#实现,32位转8位)

前面只实现了8,24位转8位byte数组。

这里实现32位bitmap转8位byte数组,代码如下:

  public byte[]  bmp2byteArr(Bitmap org_Bitmap)//返回8位byteArr
        {
        //原图针对8位和24位和32位bitmap
            Rectangle rc = new Rectangle(0, 0, org_Bitmap.Width, org_Bitmap.Height);
            System.Drawing.Imaging.BitmapData bmpdata = org_Bitmap.LockBits(rc,
                  System.Drawing.Imaging.ImageLockMode.ReadWrite,
                  org_Bitmap.PixelFormat);
            IntPtr imageptr = bmpdata.Scan0;
            int ww = org_Bitmap.Width;
            int hh = org_Bitmap.Height;
            int bytes = 0;
            if (org_Bitmap.PixelFormat == PixelFormat.Format32bppArgb)
              
            {
                bytes = ww * hh * 4;//此处针对的是32位位图
            }
            if (org_Bitmap.PixelFormat == PixelFormat.Format24bppRgb)
            {
                bytes = ww * hh * 3;//此处针对的是24位位图
            }
            if (org_Bitmap.PixelFormat == PixelFormat.Format8bppIndexed)
            {
                bytes = ww * hh;
            }


            byte[] glob_rgbOrGrey = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(imageptr, glob_rgbOrGrey, 0, bytes);
            org_Bitmap.UnlockBits(bmpdata);

            byte[] grey8 = new byte[ww * hh];
            if (org_Bitmap.PixelFormat == PixelFormat.Format24bppRgb)
            {
                for (int i = 0; i < ww; i++)
                    for (int j = 0; j < hh; j++)
                    {
                        int m = j * ww + i;
                        grey8[m] = glob_rgbOrGrey[3 * m];
                    }

                return grey8;
            }else
            if (org_Bitmap.PixelFormat == PixelFormat.Format32bppArgb)
            {
                for (int i = 0; i < ww; i++)
                    for (int j = 0; j < hh; j++)
                    {
                        int m = j * ww + i;
                        grey8[m] = glob_rgbOrGrey[4 * m];
                    }

                return grey8;
            }
            else
            {
                return glob_rgbOrGrey;
            }
               
        }

做个备份,方便查找使用。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值