繁体   English   中英

在C#中将灰度部分透明的图像转换为单色

[英]Convert grayscale partially transparent image to a single color in c#

我正在尝试创建一个函数,该函数采用灰度图像和颜色,并使用该色阴影为灰度图像着色,但保持灰度图像的阴影级别。 该功能也不应为图像的透明部分着色。 我有多个图层(多个png),稍后我将进行合并,只需要为某些图层着色即可。 我环顾四周,发现了类似的东西,但并不是我所需要的。 我知道如何使用Canvas在前端的HTML5中为用户执行此操作,但我需要一种使用后端解锁来实现相同功能的方法,我想是使用解锁位图内存调用的手动方法或ColorMatrix类。 谁能帮我,图形不是我最擅长的领域,但我正在慢慢学习。 请参阅下面的函数,以了解我在javascript中使用C#所需的功能。 做隐藏的画布工作并不重要,因为我正在服务器端进行保存以保存到PNG文件...

function drawImage(imageObj, color) {
    var hidden_canvas = document.createElement("canvas");
    hidden_canvas.width = imageObj.width;
    hidden_canvas.height = imageObj.height;
    var hidden_context = hidden_canvas.getContext("2d");

    // draw the image on the hidden canvas
    hidden_context.drawImage(imageObj, 0, 0);

    if (color !== undefined) {
        var imageData = hidden_context.getImageData(0, 0, imageObj.width, imageObj.height);
        var data = imageData.data;

        for (var i = 0; i < data.length; i += 4) {
            var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];

            //red
            data[i] = brightness + color.R;
            //green
            data[i + 1] = brightness + color.G;
            //blue
            data[i + 2] = brightness + color.B;
        }

        //overwrite original image
        hidden_context.putImageData(imageData, 0, 0);
    }

    var canvas = document.getElementById('card');
    var context = canvas.getContext('2d');
    context.drawImage(hidden_canvas, 0, 0);
};

这应该做的工作:

public static Bitmap MakeChromaChange(Bitmap bmp0, Color tCol, float gamma)
{
    Bitmap bmp1 = new Bitmap(bmp0.Width, bmp0.Height);

    using (Graphics g = Graphics.FromImage(bmp1))
    {
        float f = (tCol.R + tCol.G + tCol.B) / 765f;
        float tr = tCol.R / 255f - f;
        float tg = tCol.G / 255f - f;
        float tb = tCol.B / 255f - f;

        ColorMatrix colorMatrix = new ColorMatrix(new float[][]
        {  new float[] {1f + tr, 0, 0, 0, 0},
           new float[] {0, 1f + tg, 0, 0, 0},
           new float[] {0, 0, 1f + tb, 0, 0},
           new float[] {0, 0, 0, 1, 0},
           new float[] {0, 0, 0, 0, 1}  });

        ImageAttributes attributes = new ImageAttributes();
        attributes.SetGamma(gamma);
        attributes.SetColorMatrix(colorMatrix);

        g.DrawImage(bmp0, new Rectangle(0, 0, bmp0.Width, bmp0.Height),
            0, 0, bmp0.Width, bmp0.Height, GraphicsUnit.Pixel, attributes);
    }
    return bmp1;
}

请注意,我保留了一个gamma参数; 如果不需要,则将值保持为1f

它在起作用,先添加红色,然后添加更多红色和一些蓝色:

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

透明像素不受影响。

有关ColorMatrix更多信息,这是一个非常不错的介绍

作为一个有趣的项目,我将已知颜色应用于已知面孔:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM