gpt4 book ai didi

c# - "Colourizing".NET 中的位图

转载 作者:行者123 更新时间:2023-11-30 19:22:15 24 4
gpt4 key购买 nike

如果您有一个包含灰度图像的 System.Drawing.Bitmap 实例,是否有一种内置方法可以通过另一种颜色的影响对其进行“着色”?

例如,如果您有一张咖啡杯的黑白(灰度)图片,并且您想要以编程方式创建红色、绿色和紫色版本的单独图像。

最佳答案

我没有可提供的代码示例,但这里有一种方法可以做到这一点。将每个像素从 RGB 转换为 HSV,并更改每个像素上的色相和饱和度分量。色调控制颜色。值应保持不变。结果将是具有相同亮度和暗度但颜色不同的位图。

编辑:这是一个例子。注意色相和饱和度更新。

        public static Color ColorFromAhsb(int a, float h, float s, float b)
{

if (0 > a || 255 < a)
{
throw new Exception("a");
}
if (0f > h || 360f < h)
{
throw new Exception("h");
}
if (0f > s || 1f < s)
{
throw new Exception("s");
}
if (0f > b || 1f < b)
{
throw new Exception("b");
}

if (0 == s)
{
return Color.FromArgb(a, Convert.ToInt32(b * 255),
Convert.ToInt32(b * 255), Convert.ToInt32(b * 255));
}

float fMax, fMid, fMin;
int iSextant, iMax, iMid, iMin;

if (0.5 < b)
{
fMax = b - (b * s) + s;
fMin = b + (b * s) - s;
}
else
{
fMax = b + (b * s);
fMin = b - (b * s);
}

iSextant = (int)Math.Floor(h / 60f);
if (300f <= h)
{
h -= 360f;
}
h /= 60f;
h -= 2f * (float)Math.Floor(((iSextant + 1f) % 6f) / 2f);
if (0 == iSextant % 2)
{
fMid = h * (fMax - fMin) + fMin;
}
else
{
fMid = fMin - h * (fMax - fMin);
}

iMax = Convert.ToInt32(fMax * 255);
iMid = Convert.ToInt32(fMid * 255);
iMin = Convert.ToInt32(fMin * 255);

switch (iSextant)
{
case 1:
return Color.FromArgb(a, iMid, iMax, iMin);
case 2:
return Color.FromArgb(a, iMin, iMax, iMid);
case 3:
return Color.FromArgb(a, iMin, iMid, iMax);
case 4:
return Color.FromArgb(a, iMid, iMin, iMax);
case 5:
return Color.FromArgb(a, iMax, iMin, iMid);
default:
return Color.FromArgb(a, iMax, iMid, iMin);
}

}

private void Form1_Load(object sender, EventArgs e)
{
var bmp = new Bitmap("c:\\bw.bmp");

foreach (int y in Enumerable.Range(0, bmp.Height))
{
foreach (int x in Enumerable.Range(0,bmp.Width))
{
var p = bmp.GetPixel(x, y);
var h = p.GetHue();

var c = ColorFromAhsb(p.A, p.GetHue() + 200, p.GetSaturation() + 0.5f, p.GetBrightness());
bmp.SetPixel(x, y, c);
}
}
pictureBox1.Image = bmp;
//bmp.Dispose();

}

关于c# - "Colourizing".NET 中的位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1498832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com