1

I want to convert a jpeg file to hexadecimal format, I found some of the solutions where initially the image is converted into byte array and then to hex format.Is there any method which directly convert jpeg image to hex format in C#.

rampuriyaaa
  • 4,926
  • 10
  • 34
  • 41
  • Just to be clear, you're looking to represent the image as a string with characters in hex format? – Rotem Sep 10 '13 at 11:03
  • Then no, you must pass though byte array. See http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa for how to do that – Rotem Sep 10 '13 at 11:06
  • Hey Rotem it means that if I want to convert jpeg to hex format always I have to convert into byte array first??? – rampuriyaaa Sep 10 '13 at 11:29
  • Yes. You should also take note that both of the answers are simply converting the raw file bytes to a hex string. This is very different than encoding the pixels of the images. In this case, there is no relevance to the fact that it is an image. Whomever is reading the hex string on the other end must also know that it is a JPEG file, and load it as a JPEG, it is not raw image data. – Rotem Sep 10 '13 at 11:33

2 Answers2

8

using System.Runtime.Remoting.Metadata.W3cXsd2001 namespace :)

var str = new SoapHexBinary(File.ReadAllBytes(fName)).ToString();

or using BitConverter

var str2 = BitConverter.ToString(File.ReadAllBytes(fName));
I4V
  • 34,891
  • 6
  • 67
  • 79
1

There is no such function, but you can easily write one:

void ConvertToHex(string inputFilePath, string outputFilePath)
{
    var bytes = File.ReadAllBytes(inputFilePath);
    var hexString = string.Join("", bytes.Select(x => x.ToString("X2")));
    File.WriteAllText(outputFilePath, hexString);
}
Benoit Blanchon
  • 13,364
  • 4
  • 73
  • 81