加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在Bitmap / Image中替换特定颜色的有效方法

发布时间:2020-12-15 21:49:00 所属栏目:百科 来源:网络整理
导读:在我的灰度图片中,我需要找到特定的值并用一些颜色替换它,例如黄色.这是我现在的代码,但它并不像我需要的那么快.有没有更有效的方法来实现这一目标?我对 ColorMatrix Class有所了解,但是没有找到替换单个值而不影响整个图像的方法. unsafe{ byte stlThres =
在我的灰度图片中,我需要找到特定的值并用一些颜色替换它,例如黄色.这是我现在的代码,但它并不像我需要的那么快.有没有更有效的方法来实现这一目标?我对 ColorMatrix Class有所了解,但是没有找到替换单个值而不影响整个图像的方法.

unsafe
{
    byte stlThres = 115;

    int bytePerPixel = Image.GetPixelFormatSize(kpImageViewer1.Image.PixelFormat) / 8;
    var data = kpImageViewer1.Image.LockBits(new Rectangle(0,kpImageViewer1.Image.Width,kpImageViewer1.Image.Height),ImageLockMode.WriteOnly,kpImageViewer1.Image.PixelFormat);
    for (int y = 0; y < data.Height; y++)
    {
        byte* row = (byte*)data.Scan0 + (y * data.Stride);

        for (int x = 0; x < data.Width; x++,row += bytePerPixel)
        {
            if (row[0] == stlThres)
            {
                row[0] = 0; //b
                row[1] = 255; //g
                row[2] = 255; //r
                if (bytePerPixel == 4)
                {
                    row[3] = 255; //a
                }
            }
        }
    }
    kpImageViewer1.Image.UnlockBits(data);
}

解决方法

在4通道图像的情况下,每个像素为4个字节(每个通道8位),您可以使用由行[0]索引的256个条目查找表,并将所有四个通道同时分配为单个32位INT.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读