C# 十六进制字符串到字节图像和筛选
本文关键字:筛选 图像 到字节 十六进制 字符串 | 更新日期: 2023-09-27 18:35:06
我需要一些帮助将十六进制字符串转换为图像
做了一些研究,我想出了这个代码:
private byte[] HexString2Bytes(string hexString)
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x*2, 2),16);
}
return bytes;
}
public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
try
{
System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
_FileStream.Write(_ByteArray, 0, _ByteArray.Length);
_FileStream.Close();
return true;
}
catch (Exception _Exception)
{
MessageBox.Show(_Exception.Message);
}
return false;
}
问题是生成的图像几乎都是黑色的,我想我需要应用一些过滤器来更好地转换灰度(因为原始图像仅是灰度)
谁能帮我?
非常感谢
您无需应用任何筛选器。我猜您作为输入传递的hexString
变量只是一个黑色图像。以下内容对我很有用:
class Program
{
static void Main()
{
byte[] image = File.ReadAllBytes(@"c:'work'someimage.png");
string hex = Bytes2HexString(image);
image = HexString2Bytes(hex);
File.WriteAllBytes("visio.png", image);
Process.Start("visio.png");
}
private static byte[] HexString2Bytes(string hexString)
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}
private static string Bytes2HexString(byte[] buffer)
{
var hex = new StringBuilder(buffer.Length * 2);
foreach (byte b in buffer)
{
hex.AppendFormat("{0:x2}", b);
}
return hex.ToString();
}
}