6

how do I convert a byte[] to an Image in .NET Core?

I found this:

using (var ms = new MemoryStream(byteArrayIn))
{
    return Image.FromStream(ms);
}

but it seems like Image doesnt exist in .NET-Core.

4
  • 2
    No indeed it is not released yet. you can use the library ImageSharp Commented Jun 13, 2017 at 10:59
  • oh thats weird. If you would answer this question I could mark it as correct Commented Jun 13, 2017 at 10:59
  • 1
    The code from the question works fine now in .NET-Core. Commented May 14, 2020 at 21:17
  • @ZbigniewWiadro nice to hear that :-) You should probably answer this question Commented May 15, 2020 at 12:39

4 Answers 4

6

No indeed it is not released yet. you can use the library ImageSharp.

Sign up to request clarification or add additional context in comments.

Comments

3

To return an image from a byte array, you can either:

  1. return base64

    Byte[] profilePicture = await _db.Players
                                     .Where(p => p.Id == playerId)
                                     .Select(p => p.ProfilePicture)
                                     .FirstOrDefaultAsync();
    
    return Ok(Convert.ToBase64String(profilePicture));
    

    And then you can use any online tool that converts base64 to image to test it.

  2. or return FileContentResult File(byte[] fileContents, string contentType)

    return File(profilePicture, "image/png");
    

    You should be able to test this from Postman or anything similar as the picture will show up in the body of the response there.

Comments

1

You'll need to install the System.Drawing.Common NuGet package. Then you may use next function:

    public static System.Drawing.Image ImageFromByteArray(byte[] src)
    {
        MemoryStream ms = new MemoryStream(src);
        System.Drawing.Image retval = System.Drawing.Image.FromStream(ms);
        return retval;
    }

Comments

-2

If you are using javascript

img tag:

html

<img id="logoPic" src="" />

js:

document.getElementById("logoPic").src = "data:image/png;base64," + yourByte;

with insertCell:

row.insertCell(2).innerHTML = "<img src='" + "data:image/png;base64," + yourByte + "'></>";

with td:

"<td>"+ "<img src='" + "data:image/png;base64," + yourByte + "'></>" + "</td>"

If you are using jquery:

html

<img id="logoPic" src="" />

JQuery:

$('#logoPic').attr('src', `data:image/png;base64,${YourByte}`);

2 Comments

this question about dotnet core dear @carlos
you can use JavaScript in donet core dear @R.Akjlaghi, donet core is the environment.

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.