1

OK. I have a basic MVC5 web app. I store images as binary in SQL DB. All good so far.

I can upload different image types: png, jpg, gif ...

My question when I read the image (binary from db) and show it, how can I dynamically format the data:image/gif;base64,XXXXXXXXXXXXXXXXXXXXXXXXX ?

More exactly, how can I get the it's type, image/gif or image/png or image/jpg ... from that binary image?

1 Answer 1

1

Using ImageCodecInfo:

byte[] bytes; //get from DB
...
using (var ms = new System.IO.MemoryStream(bytes)) 
{
    using(var img = Image.FromStream(ms)) 
    {
        var type = GetMimeType(img);
    }
}

public static string GetMimeType(Bitmap image)
{
    var type = ImageCodecInfo.GetImageDecoders().FirstOrDefault(codec => codec.FormatID == image.RawFormat.Guid);

    return type != null ? type.MimeType : "image/unknown";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.