c# - 如何将位图照片转换为十六进制颜色代码?
问题描述
我正在尝试为我的简历创建一个程序但是我在将灰度照片的位图照片转换为十六进制或更好地调用它的代码时遇到问题,如果颜色是任何可以帮助我的人?
我试图用base64string转换它,但它没有用。
openFileDialog1=new OpenFileDialog();
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Image";
dlg.Filter = "bmp files (*.bmp)|*.bmp";
if (dlg.ShowDialog() == DialogResult.OK)
{
Rectangle bounds = Screen.GetBounds(Point.Empty);
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
// Convert the image to byte[]
System.IO.MemoryStream stream = new System.IO.MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
// Write the bytes (as a Base64 string) to the textbox
textBox1.Text = base64String.ToString();
我希望看到一堆像A9C或255这样的数字,但我看到的东西什么都没有。
解决方案
它与您的代码中的 .bmp 文件一起使用,并提供 AARRGGBB 像素代码。
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_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);
var str = string.Join(Environment.NewLine,
colorCodes.Select<int[], string>(line => string.Join(" ", line.Select<int, string>(code => string.Format("{0:X8}", code))))); // string.Format("{0:X6}", code & 0x00FFFFFF) if you want RRGGBB format
textBox1.Text = str; // requires textBox1.Multiline = true, better have monospaced font
}
}
}
private int[][] GetColorCodes(string path)
{
var bitmap = new Bitmap(path);
return Enumerable.Range(0, bitmap.Height)
.Select<int, int[]>(y => Enumerable.Range(0, bitmap.Width)
.Select<int, int>(x => bitmap.GetPixel(x, y).ToArgb())
.ToArray())
.ToArray();
}
}
}
推荐阅读
- c# - 使用 MvvmCross 将图标添加到 TabLayout
- symfony - Doctrine OneToOne 关系双向
- jquery - 为不同的数据库实体显示相同的模式形式
- python - 此 python 有效,但正在寻找更优雅的解决方案(Try and Catch with 1/0 hack)
- excel - 如何粘贴到 Excel 过滤器中的可见单元格中?
- sql - 如何获得每个客户每天花费的最大时间
- c# - 用值展平表达式参数
- javascript - 在不考虑时区的情况下将字符串转换为日期 - 打字稿
- java - 使用 ContentResolver 和 openInputStream() (Android)
- excel - 使用 COUNTIF / VLOOKUP 进行库存管理