2

16進文字列を画像に変換するのに助けが必要です

いくつかの調査を行って、私はこのコードにたどり着きました:

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

問題は、結果の画像がほぼすべて黒であり、グレースケールをより適切に変換するためにいくつかのフィルターを適用する必要があると思います(元の画像はグレースケールのみであるため)

誰か助けてもらえますか?

どうもありがとう

4

1 に答える 1

4

フィルタを適用する必要はありません。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();
    }
}
于 2012-05-22T08:10:24.467 に答える