求助:将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
0xFFto 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
- White (RGB 255,255,255) becomes
- Output Decimal: Instead of formatting as hex with
string.Format("{0:X8}", code), we just convert the inverted integer directly to a string withToString().
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
相关产品推荐
相关产品推荐

