【问题标题】:c# hex string to byte image and filteringc# 十六进制字符串到字节图像和过滤
【发布时间】:2012-05-28 17:05:03
【问题描述】:

我需要一些帮助将十六进制字符串转换为图像

做了一些研究,我想出了这个代码:

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;
 }

问题是生成的图像几乎全是黑色的,我想我需要应用一些过滤器来更好地转换灰度(因为原始图像只有灰度)

谁能帮帮我?

非常感谢

【问题讨论】:

  • 等待 - 生成的二进制文件是否正常?我的意思是,您是否发现您发布的功能有任何问题?
  • 但是您展示的方法只是将字符串转换为字节数组。您接下来做了什么来创建图像? Marshal.Copy?

标签: c# image filtering


【解决方案1】:

您无需应用任何过滤器。我猜您作为输入传递的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();
    }
}

【讨论】:

  • 这不是黑色图像,因为我可以看到一些东西,但亮度非常低,几乎全黑
  • 嗯,我不知道,那肯定还有其他的东西,还有你的代码的其他部分你没有显示。我发布的代码在这里 100% 有效。我已经用输入图像对其进行了测试,它生成了完全相同的输出图像。我不知道如何进一步帮助您。
  • 该代码适用于所有“正常”彩色图像,但我的只有灰度图像,结果几乎全是黑色,而不是多种灰度
  • 我明白了。您能否在某处上传一个示例灰度图像,以便我重现该问题?
  • 是的,但我没有原始图像,我从这里的十六进制代码link 开始,生成的图像是这个link
猜你喜欢
  • 2014-10-29
  • 2012-01-24
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 2011-03-01
相关资源
最近更新 更多