Search code examples
c#imagehex

Convert Hex to Image in C#


I have this hex data, 0xFFD8FFE000104A46494600..., I have that in a string, in the xaml of my WPF app I have an <Image/> where this encoded image needs to end up with. I have several questions about this.

  1. The biggest problem, I just cannot find a way to decode it, I do not understand how it works either, I just know that I have a string and I need to end up with an image, I do not know if that image needs to be saved somewhere, or that I can directly add the image to the <Image/> in the actual script... I need help with this, I'd just like a method where I can give the string with it and it returns an image I can use.

  2. What is the best way to do it? Like for example if it is a profile picture on different pages, should I save it somewhere in a way or have the string somewhere and decode it the whole time or?..

Note: The hex data is right, I used this website with this input + output: click to see my test


Solution

  • Basically, what you can do is convert hex string to byte array and then make BitmapImage and set that BitmapImage as source for your Image control.

    Converting hex string to byte array can be done like this (source):

    public static byte[] StringToByteArray(String hex)
    {
      int NumberChars = hex.Length;
      byte[] bytes = new byte[NumberChars / 2];
      for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
      return bytes;
    }
    

    After that, you need to make BitmapImage from byte array. You can do it like this (source):

    public BitmapImage ToImage(byte[] array)
    {
        using (var ms = new System.IO.MemoryStream(array))
        {
            var image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad; // here
            image.StreamSource = ms;
            image.EndInit();
            return image;
        }
    }
    

    Then you need to set BitmapImage as source for your Image control. You can do it like this:

    string hexData = "FFD8FFE000104A46494600...";
    byte[] imageData = StringToByteArray(hexData);
    BitmapImage bitmapImage = ToImag(imageData);
    
    // you have to have <Image x:Name="imageControl" /> in your XAML
    imageControl.Source = bitmapImage;
    

    Hope this works. Can't really try it out now. Way in which you are storing and loading pictures is different topic.

    EDIT:
    To sum up discussion from comments and chat... For this to work check if hex string is valid (if number of chars is even number, if it contains only 0-9 and A-F (so no spaces, delimiters and such), and that 0x is removed). Little workaround if length is odd number, try adding 0 at the end of hex string.