Introduction:
Images play a crucial role in enhancing the visual appeal of web applications. In this article, we will explore the process of saving and retrieving images from a database in an ASP.NET application using C# coding. The focus will be on dynamically displaying these images within a div container. Let's dive into the details!
Setting Up the Environment:
To start, we need a basic setup consisting of four controllers: two textboxes, one file uploader, and one button control. These will be responsible for handling ImageID, Image Name, and uploading images from the user's device.
- TextBox is used to display ImageID is nothing but a Auto Generate Number,
- TextBox is used to enter Image Name
- Fileuploader control is used to choose Image from your device
Create Image Database
HTML Page Structure:
The HTML page structure involves creating a table with rows for Image ID, Image Name, and the FileUploader control. The button click event triggers the image-saving functionality. Additionally, a div container named "divimg" is declared, where the images will be dynamically displayed.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style>
---------- CSS Code Here----------
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="margin:30px 40px 0px 20px;">
<table id="tableimg">
<tr>
<th colspan="2">Save and Retrieve Image from Database</th>
</tr>
<tr>
<td class="row1">
Enter Image ID :
</td>
<td class="row2">
<asp:TextBox ID="txtimageID" runat="server" CssClass="txt" BackColor="Silver"
ReadOnly="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="row1">
Enter Image Name :
</td>
<td class="row2">
<asp:TextBox ID="txtimagename" runat="server" CssClass="txt"></asp:TextBox>
</td>
</tr>
<tr>
<td class="row1">
Choose Image :
</td>
<td class="row2">
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="txt" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btn_saveimage" runat="server" Text="Image Save"
onclick="btn_saveimage_Click" />
</td>
</tr>
</table>
</div>
<br />
<div id="divimg" runat="server"></div>
</form>
</body>
</html>
CSS Styling:
Proper styling is essential for an aesthetically pleasing user interface. The CSS code defines the styles for various elements, including the table, rows, textboxes, and the dynamic image container.
<style type="text/css">
#tableimg
{
border-collapse:collapse;
width:600px;
}
#tableimg th
{
padding:5px 10px 5px 10px;
background-color:#222;
color:#fff;
border:1px solid #222;
}
.row1, .row2, .ImageBox
{
border:1px solid #222;
}
.row1, .row2
{
padding:3px;
text-align:left;
}
.row2
{
width:350px;
}
.txt
{
width:300px;
}
.txt, .ImageBox, ImageBox:hover
{
padding:5px;
}
.ImageBox, ImageBox:hover
{
width:150px;
height:150px;
margin:5px;
}
.ImageBox:hover
{
border:1px solid #e4e4e4;
background-color:#222;
}
</style>
C# Coding : Namespace
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
C# Coding: Image Handling:
The C# code is responsible for handling the backend logic. It includes functions to generate ImageIDs, display images dynamically, and save images to the database. The GetImageID method ensures that ImageIDs are auto-generated, and the DisplayImage method dynamically creates image controls and displays them within the div container.
private int GetImageID()
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("select Isnull(MAX(imgid),10000) from image", con);
int i = Convert.ToInt32(cmd.ExecuteScalar());
i++;
return i;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
private void DisplayImage()
{
SqlDataAdapter da = new SqlDataAdapter("Select * from Image", con);
DataSet ds=new DataSet();
da.Fill(ds);
if(ds.Tables[0].Rows.Count>0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
// its required type casting to convert from Dataset type to binary
byte[] bytes = (byte[])ds.Tables[0].Rows[i]["image"];
//convert to string
string strbase64 = Convert.ToBase64String(bytes);
// this Image Control is creating dynamically and add to divimg which was already declared in html
Image img = new Image();
img.ID = i.ToString();
img.CssClass = "ImageBox";
img.ImageUrl = "data:Image/png;base64," + strbase64;
divimg.Controls.Add(img);
}
}
}
Page Loading and Image Saving:
In the Page_Load event, the DisplayImage method is called to showcase existing images. The btn_saveimage_Click event is triggered when the user uploads a new image, ensuring proper validation and saving the image data to the database..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayImage();
int ImgID = GetImageID();
txtimageID.Text = ImgID.ToString();
}
}
protected void btn_saveimage_Click(object sender, EventArgs e)
{
try
{
HttpPostedFile postfile = FileUpload1.PostedFile;
string filename = Path.GetFileName(postfile.FileName);
string fileExtension = Path.GetExtension(filename);
int filesize = postfile.ContentLength;
if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".png" || fileExtension.ToLower() == ".gif" || fileExtension.ToLower() == ".bmp")
{
Stream imgstream = postfile.InputStream;
BinaryReader binaryreader = new BinaryReader(imgstream);
byte[] imgbytes = binaryreader.ReadBytes((int)imgstream.Length);
//Save Image Data into Database
con.Open();
SqlCommand cmd = new SqlCommand("Insert into Image(imgid, imagename, image) values('" + txtimageID.Text + "','" + txtimagename.Text + "',@image)", con);
cmd.Parameters.AddWithValue("@image", SqlDbType.Binary).Value = imgbytes;
int i=cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{
DisplayImage();
int ImgID = GetImageID();
txtimageID.Text = ImgID.ToString();
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
Conclusion:
Mastering the art of dynamic image display in ASP.NET using C# opens up exciting possibilities for creating visually appealing and interactive web applications. By understanding the integration of HTML, CSS, and C# coding, developers can build robust image management systems that enhance the user experience.
This tutorial provides a comprehensive guide to save, retrieve, and dynamically display images, empowering developers to incorporate rich media seamlessly into their ASP.NET applications.
0 Comments