Wednesday, August 5, 2015

C# Convert image to hex and vice versa

    Here I want to show you how to convert image to hex format and vice versa  using C# language

To convert image to hex data we need only one line of code.
public void ConvertImageToHex(string filePath){
    return BitConverter.ToString(File.ReadAllBytes(fName));
} 
To bring back hex string to image we need to do a little bit more
// saves hex string image to the pathToSave
public static void SaveImageFromHex(string hex, string pathToSave)
{
    // Call function to Convert the hex data to byte array
    byte[] newByte = ToByteArray(hexImgData);
    MemoryStream memStream = new MemoryStream(newByte);

    // Save the memorystream to file
    Bitmap.FromStream(memStream).Save(pathToSave);
}

// Function converts hex data into byte array
private static byte[] ToByteArray(String HexString)
{
    int NumberChars = HexString.Length;
    byte[] bytes = new byte[NumberChars / 2];

    for (int i = 0; i < NumberChars; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
    }
    return bytes;
}
original posts: http://www.nullskull.com/faq/40/convert-hex-image-data-to-jpeg.aspx http://stackoverflow.com/questions/18717182/convert-jpeg-image-to-hex-format

No comments:

Post a Comment