0

I have been given a text file containing hex data which I know forms a jpeg image. Below is an example of the format:

FF D8 FF E0 00 10 4A 46 49 46 00 01 02 00 00 64 00 64 00 00 FF E1 00 B8 45 78 69 00 00 4D

This is only a snippet but you get the idea.

Does anyone know how I could convert this back into the original jpeg?

Theolodis
  • 4,977
  • 3
  • 34
  • 53
Bottleposh
  • 13
  • 2

1 Answers1

0

To convert from a hex string to a byte you use the Convert.ToByte with a base 16 parameter.

To convert a byte array to a Bitmap you put it in a Stream and use the Bitmap(Stream) constructor:

using System.IO;
//..

string hexstring = File.ReadAllText(yourInputFile);
byte[] bytes = new byte[hexstring.Length / 2];
for (int i = 0; i < hexstring.Length; i += 2)
     bytes[i / 2] = Convert.ToByte( hexstring.Substring(i, 2), 16);
using (MemoryStream ms = new MemoryStream(bytes))
{
   Bitmap bmp = new Bitmap(ms);
   // now you can do this: 
   bmp.Save(yourOutputfile, System.Drawing.Imaging.ImageFormat.Jpeg);
   bmp.Dispose();   // dispose of the Bitmap when you are done with it!
   // or that:
   pictureBox1.Image = bmp;  // Don't dispose as long as the PictureBox needs it!
}

I guess that there are more LINQish way but as long as it works..

TaW
  • 53,122
  • 8
  • 69
  • 111