asp.net display image from byte array

I have a byte array and trying to display image from that.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq;

namespace RealPortableTerminal
{
public partial class resim : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        PortableTerminalDbEntities entity = new PortableTerminalDbEntities();
        byte[] arr = (from b in entity.Sicil where b.Id == 31 select b.Fotograf).First();

        Image rImage = null;
        using (MemoryStream ms = new MemoryStream(arr))
        {
            rImage = Image.FromStream(ms);
        }
    }
}
}

It underlines FromStream and says ‘System.Web.UI.WebControls.Image’ does not contain a definition for ‘FromStream’. It seems adding System.Data.Linq reference did not changed anything. Am I missing something ? Btw I am pretty sure I take byte array from database correctly.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Another way to do it is to convert your byte array into a base 64 string and assign that to the ImageUrl property of rImage, like so:

rImage.ImageUrl = "data:image;base64," + Convert.ToBase64String(arr);

You don’t need the intermediate MemoryStream or a separate page…if the byte array is in an image format the browser supports, it will display. Good luck.

Method 2

<img id="img" runat="server" alt=""/>

In code behind
string base64String = Convert.ToBase64String(arr, 0, arr.Length);
img.Src = "data:image/jpg;base64," + base64String;

You wouldn’t need MemoryStream.

Method 3

You’re probably thinking of System.Drawing.Image; that class supports FromStream.

This forum post shows you a few ways to load dynamic images in WebForms.

Probably the simplest way would be to create a separate aspx page which loads your image as you’re doing here and use Response.BinaryWrite to save it to the response stream, then in the page you’re working on, create an Image control which uses the new aspx page as its image URL. You can of course use query string parameters if you need to load a variety of images.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x