Search code examples
c#colorshexrgb

Convert ARGB to Hex with 6 Value


Using C# I was trying to devide a photo in more than Photo. in Each Photo i have a piece colour. The way I am doing it have a problem and need your kind advice. the Problem is my Photo name will have an 8 ARGB Values! but i want just 6 values! i want the filename to take into account the color RGB value without the alpha.

public class PNG2PNGS
{
    public static void Convert(string sourcePath)
    {
        foreach (var fileName in Directory.GetFiles(sourcePath, "*.png"))
        {
            Bitmap bitmap = new Bitmap(fileName);
            List<Color> colors = new List<Color>();

            for (int i = 0; i < bitmap.Width; i++)
            {
                for (int j = 0; j < bitmap.Height; j++)
                {
                    Color color = bitmap.GetPixel(i, j);
                    if (!colors.Contains(color))
                    {
                        colors.Add(color);
                    }
                }
            }

            foreach (Color color in colors)
            {
                Bitmap bitmap2 = new Bitmap(bitmap.Width, bitmap.Height, bitmap.PixelFormat);
                for (int i = 0; i < bitmap.Width; i++)
                {
                    for (int j = 0; j < bitmap.Height; j++)
                    {
                        if (bitmap.GetPixel(i, j) == color)
                        {
                            bitmap2.SetPixel(i, j, color);
                        }
                        else
                        {
                            bitmap2.SetPixel(i, j, Color.Transparent);
                        }
                    }
                }
                
                bitmap2.Save(Path.Combine(Path.GetDirectoryName(fileName), $"{Path.GetFileNameWithoutExtension(fileName)}_{color.ToArgb().ToString("X6")}.png"), ImageFormat.Png);
            }

            bitmap.GetPixel(0,0);
        }
    }
}

Solution

  • If I understood correctly, you want the filename to take into account the color RGB value without the alpha.

    You can use a temporary that will be exactly that - the color with 0 for the alpha channel.

    Then use your print format specifier as you already did:

    Color color = Color.FromArgb(0x0A, 0x0B, 0x0C, 0x0D);
    //...
    Color colorNoAlpha = Color.FromArgb(0, color.R, color.G, color.B);
    Console.WriteLine(colorNoAlpha.ToArgb().ToString("X6"));
    

    Output:

    0B0C0D
    

    (In your code, add the line initializing colorNoAlpha before saving the file, and in the file save statement replace color with colorNoAlpha).