How to retrieve binary image from database using C# in ASP.NET

I need to retrieve a binary image from the database.

My queries are as below.

SqlConnection con = new SqlConnection(@"Data Source=localhost;Initial Catalog=MyGames;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select blueBallImage from CorrespondingBall WHERE objective = Default Ball", con);

I do not know how to retrieve blueBallImage which is a binary image.

After I have retrieve it successfully, I need to add a text onto the image using a dropdownlist which contain the text. The codes are as below.

Bitmap bmp = new Bitmap(@"C:Usersapr13mpsipDocumentsVisual Studio 2012WebSitesCorrespondingBallWebSiteImagesblueBallDefault.png");

For the time being, I do not know how to retrieve the image. Therefore, I hard coded it which I do not want. I want to retrieve it from database.
Graphics gra = Graphics.FromImage(bmp);

gra.DrawString(ddlCharacter.Text, new Font("Verdana", 18), Brushes.Black, new PointF(4, 6));

MemoryStream ms1 = new MemoryStream();
bmp.Save(ms1, ImageFormat.Png);
var base64Data = Convert.ToBase64String(ms1.ToArray());
imgImage.ImageUrl = "data:image/png;base64," + base64Data;

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

Here is a basic sample to load an image from database quickly and load into a html image source in ASP. Please tell me if it works for you 😉

//Get byte array from image file in the database with basic query
SqlDataAdapter myAdapter1 = new SqlDataAdapter("Select [logo] FROM [dbo].[tblCompanyInfo]", GlobalUser.currentConnectionString);
DataTable dt = new DataTable();
myAdapter1.Fill(dt);

foreach (DataRow row in dt.Rows)
{
    // Get the byte array from image file
    byte[] imgBytes = (byte[]) row["logo"];

    // If you want convert to a bitmap file
    TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
    Bitmap MyBitmap = (Bitmap)tc.ConvertFrom(imgBytes);

    string imgString = Convert.ToBase64String(imgBytes);
    //Set the source with data:image/bmp
    imgLogoCompany.Src = String.Format("data:image/Bmp;base64,{0}"", imgString);
}

Method 2

you need to made an ASP.NET handler (*.ASHX) that serves the bytes of the image

<img src="ImageHandler.ashx?id=<%=id%>" />

In image handler you need to code like this
public class ImageHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Load the image (see previous code sample)
        byte[] data = Convert.FromBase64String(encodedString);

        // Display the image
        context.Response.OutputStream.Write(data, 0, data.Length);
        context.Response.ContentType = "image/JPEG";
    }
}

please refer this for more info Image from Database

Method 3

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Connect();
    }

    try
    {
        cm = new SqlCommand("select profile_pic from TblNewMemberRegistration where    user_name='<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8abadbcb0b9b6abb0ad98b5b9b1b4bab7a0f6bbb7b5">[email protected]</a>'", cn);
        byte[] b = (byte[])cm.ExecuteScalar();
        stream.Write(b, 0, b.Length);
        Bitmap bm = new Bitmap(stream);
        Response.ContentType = "image/gif";
        bm.Save(Response.OutputStream, ImageFormat.Gif);
    }
    catch(Exception ex) 
    {
        Response.Write(ex.Message);
    }
    finally
    {
        cn.Close();
        stream.Close();
    }
}
protected void Connect()
{
    cn = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
    cn.Open();


}


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