You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:将BMP文件解析后的十六进制结果转为十进制

Convert BMP Pixel Hex Values to Inverted Decimal Grayscale

Hey there! It looks like you're trying to switch from displaying BMP pixel values as hex to inverted decimal grayscale (where white = 0 and black = 255). Let's adjust your code to make that happen seamlessly.

Modified Code

Here's the updated version of your click handler (I fixed the tiny typo in "Choose" too 😉):

private void ChooseBtn_Click(object sender, EventArgs e)
{
    using (OpenFileDialog dlg = new OpenFileDialog())
    {
        dlg.Title = "Open Image";
        dlg.Filter = "bmp files (*.bmp)|*.bmp";
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            var colorCodes = this.GetColorCodes(dlg.FileName);
            // Convert each ARGB code to inverted decimal grayscale
            var str = string.Join(Environment.NewLine, 
                colorCodes.Select(line => string.Join(" ", 
                    line.Select(code => 
                    {
                        // Extract red component (matches green/blue for grayscale images)
                        int grayValue = (code >> 16) & 0xFF;
                        // Invert to get white = 0, black = 255
                        int invertedDecimal = 255 - grayValue;
                        return invertedDecimal.ToString();
                    }))));
            textBox1.Text = str; 
            // Remember: textBox1.Multiline = true + monospaced font works best here
        }
    }
}

private int[][] GetColorCodes(string path)
{
    var bitmap = new Bitmap(path);
    return Enumerable.Range(0, bitmap.Height)
        .Select(y => Enumerable.Range(0, bitmap.Width)
            .Select(x => bitmap.GetPixel(x, y).ToArgb()).ToArray()).ToArray();
}

Key Changes Explained

Let's break down what's different and why it works:

  • Extract Grayscale Value: For each pixel's ARGB integer, we shift right by 16 bits and mask with 0xFF to grab the red component. Since you're working with grayscale images, red, green, and blue values are identical—so any of these components would work.
  • Invert the Scale: Subtract the grayscale value from 255 to flip the range:
    • White (RGB 255,255,255) becomes 255 - 255 = 0
    • Black (RGB 0,0,0) becomes 255 - 0 = 255
  • Output Decimal: Instead of formatting as hex with string.Format("{0:X8}", code), we just convert the inverted integer directly to a string with ToString().

Quick Note

If your BMP isn't strictly grayscale, this code will still work but will use the red component as the base value. If you need to handle color images (e.g., use the average of RGB values), just let me know and I can tweak it further!

内容的提问来源于stack exchange,提问作者Armin Shabani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:36:10