本文介绍了C#十六进制字符串到字节图像和过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need some help in converting a hex string into an image

做一些研究,我想到了这段代码:

doing some researches i came up to this code:

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

问题在于生成的图像几乎全是黑色,我想我需要应用一些滤镜以更好地转换灰度(因为原始图像仅是灰度的)

The problem is that the resulting image is almost all black and i guess i need to apply some filters to better translate the gray-scale (since the original image is in gray-scale only)

有人可以帮助我吗?

非常感谢

推荐答案

您不需要应用任何过滤器.我猜想您作为输入传递的 hexString 变量只是一个黑色图像.以下对我有用:

You don't need to apply any filters. I guess that the hexString variable that you are passing as input is simply a black image. The following works great for me:

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

这篇关于C#十六进制字符串到字节图像和过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:46