Tony Clifton
Tony Clifton

Reputation: 703

Convert string to image from SQL

In my sql table I have a varchar that represents an image. The string looks like this:

255 216 255 224 0 16 74 70 73 70 0 1 1 1 0 96 0 96 0 0 255 219 0 67 ...

saved as a .txt it is around 20KB in size.

First question: what type of string is this? I couldn't find anything online. Looks to me like RGB values because 255 is the highest number in there.

How can I use C# (ASP.net MVC to be precise) to convert this string format to an actual image again?

Thank you.

UPDATE

Talked to the developer:

the image is pulled from the Active Directory thumbnailPhoto attribute and is stored as a string. Maybe it's best to convert the source instead.

Upvotes: 0

Views: 973

Answers (1)

Tyler Jennings
Tyler Jennings

Reputation: 8911

You'll need to know the encoding. As an example, here is how I am decoding a binary string into a tiff image:

    private static BlockUIContainer ConvertBinaryToImageUIContainer(string binary)
    {
        byte[] binaryData = Convert.FromBase64String(binary);
        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.StreamSource = new MemoryStream(binaryData);
        bitmapImage.EndInit();
        BlockUIContainer container = new BlockUIContainer();
        container.Child = new System.Windows.Controls.Image { Source = bitmapImage };
        return container;
    }

Take the binary string and depending on the encoding convert it to byte. In my case it was a Base64String. Create a new image and create a memorystream as the source. I, optionally, set mine in a BlockUIContainer to display in a WPF app, but you could use the bitmapImage or byte[] data how you wish. Hope this helps.

Upvotes: 2

Related Questions