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.

Moritz Schmidt
  • 2,635
  • 3
  • 27
  • 51

4 Answers4

6

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

Stacked
  • 6,892
  • 7
  • 57
  • 73
Lenny32
  • 624
  • 6
  • 15
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.

Ahmed Mansour
  • 527
  • 5
  • 13
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;
    }
Matias Masso
  • 1,670
  • 3
  • 18
  • 28
-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}`);