Hi chukaeke,
I have created sample code which fullfill your requirement.Please refer carefully and Implement in your code.
HTML
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
<div>
<asp:GridView ID="gridInformation" runat="server" AutoGenerateColumns="false" Font-Names="Arial"
OnRowDataBound="gridInformation_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="FileName" HeaderText="Image Name" />
<asp:TemplateField HeaderText="Pics" ItemStyle-Height="100" ItemStyle-Width="100">
<ItemTemplate>
<asp:Label ID="lblPath" Visible="false" Text='<%#Eval("FilePath") %>' runat="server" />
<asp:Image ID="empimage" runat="server" ImageUrl='<%# Eval("FilePath", GetUrl("{0}")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExportExcel" CommandArgument="Excel" runat="server" Text="Export-Excel"
OnClick="Export_Grid" />
</div>
</form>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GetImage();
}
}
private void GetImage()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string strQuery = "select * from [Images]";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
gridInformation.DataSource = dt;
gridInformation.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk Temp.
FileUpload1.SaveAs(Server.MapPath("Images/" + FileName));
//Add Entry to DataBase
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
string strQuery = "insert into [Images] (FileName, FilePath) values(@FileName, @FilePath)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("@FileName", FileName);
cmd.Parameters.AddWithValue("@FilePath", "Files/" + FileName);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
public void GenerateThumbNail(string sourcefile, string destinationfile, int width)
{
if (File.Exists(Server.MapPath(sourcefile)))
{
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(sourcefile));
int srcWidth = image.Width;
int srcHeight = image.Height;
int thumbWidth = width;
int thumbHeight;
Bitmap bmp;
if (srcHeight > srcWidth)
{
thumbHeight = (srcHeight / srcWidth) * thumbWidth;
bmp = new Bitmap(thumbWidth, thumbHeight);
}
else
{
thumbHeight = thumbWidth;
thumbWidth = (srcWidth / srcHeight) * thumbHeight;
bmp = new Bitmap(thumbWidth, thumbHeight);
}
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
bmp.Save(Server.MapPath(destinationfile));
bmp.Dispose();
image.Dispose();
DeleteTempImage(sourcefile, destinationfile);
}
}
private void DeleteTempImage(string sourcefile, string destinationfile)
{
string directoryPath = Server.MapPath(sourcefile);
File.Delete(directoryPath);
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void Export_Grid(object sender, EventArgs e)
{
try
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=EmployeeInfo.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gridInformation.AllowPaging = false;
this.GetImage();
for (int i = 0; i < gridInformation.Rows.Count; i++)
{
GridViewRow row = gridInformation.Rows[i];
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
}
gridInformation.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
catch (Exception)
{
}
}
protected string GetUrl(string imagepath)
{
string[] splits = Request.Url.AbsoluteUri.Split('/');
if (splits.Length >= 2)
{
string url = splits[0] + "//";
for (int i = 2; i < splits.Length - 1; i++)
{
url += splits[i];
url += "/";
}
return url + imagepath;
}
return imagepath;
}
protected void gridInformation_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string imageName = (e.Row.FindControl("lblPath") as Label).Text;
string[] filename = imageName.Split('/');
// 70 is define image size.
GenerateThumbNail("Images/" + filename[1], imageName, 70);
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
Me.GetImage()
End If
End Sub
Private Sub GetImage()
Dim dt As DataTable = New DataTable()
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim strQuery As String = "select * from [Images]"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
Dim con As SqlConnection = New SqlConnection(strConnString)
Dim sda As SqlDataAdapter = New SqlDataAdapter()
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
gridInformation.DataSource = dt
gridInformation.DataBind()
Catch ex As Exception
Response.Write(ex.Message)
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Sub
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
If FileUpload1.PostedFile IsNot Nothing Then
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
FileUpload1.SaveAs(Server.MapPath("Images/" & FileName))
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim con As SqlConnection = New SqlConnection(strConnString)
Dim strQuery As String = "insert into [Images] (FileName, FilePath) values(@FileName, @FilePath)"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("@FileName", FileName)
cmd.Parameters.AddWithValue("@FilePath", "Files/" & FileName)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
con.Close()
con.Dispose()
End Try
End If
End Sub
Public Sub GenerateThumbNail(ByVal sourcefile As String, ByVal destinationfile As String, ByVal width As Integer)
If File.Exists(Server.MapPath(sourcefile)) Then
Dim image As System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath(sourcefile))
Dim srcWidth As Integer = image.Width
Dim srcHeight As Integer = image.Height
Dim thumbWidth As Integer = width
Dim thumbHeight As Integer
Dim bmp As Bitmap
If srcHeight > srcWidth Then
thumbHeight = (srcHeight / srcWidth) * thumbWidth
bmp = New Bitmap(thumbWidth, thumbHeight)
Else
thumbHeight = thumbWidth
thumbWidth = (srcWidth / srcHeight) * thumbHeight
bmp = New Bitmap(thumbWidth, thumbHeight)
End If
Dim gr As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bmp)
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High
Dim rectDestination As System.Drawing.Rectangle = New System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight)
gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel)
bmp.Save(Server.MapPath(destinationfile))
bmp.Dispose()
image.Dispose()
DeleteTempImage(sourcefile, destinationfile)
End If
End Sub
Private Sub DeleteTempImage(ByVal sourcefile As String, ByVal destinationfile As String)
Dim directoryPath As String = Server.MapPath(sourcefile)
File.Delete(directoryPath)
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub
Protected Sub Export_Grid(ByVal sender As Object, ByVal e As EventArgs)
Try
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=EmployeeInfo.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Dim sw As StringWriter = New StringWriter()
Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
gridInformation.AllowPaging = False
Me.GetImage()
For i As Integer = 0 To gridInformation.Rows.Count - 1
Dim row As GridViewRow = gridInformation.Rows(i)
row.Attributes.Add("class", "textmode")
Next
gridInformation.RenderControl(hw)
Dim style As String = "<style> .textmode { mso-number-format:\@; } </style>"
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
Catch ex As Exception
End Try
End Sub
Protected Function GetUrl(ByVal imagepath As String) As String
Dim splits As String() = Request.Url.AbsoluteUri.Split("/"c)
If splits.Length >= 2 Then
Dim url As String = splits(0) & "//"
For i As Integer = 2 To splits.Length - 1 - 1
url += splits(i)
url += "/"
Next
Return url & imagepath
End If
Return imagepath
End Function
Protected Sub gridInformation_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim imageName As String = (TryCast(e.Row.FindControl("lblPath"), Label)).Text
Dim filename As String() = imageName.Split("/"c)
GenerateThumbNail("Images/" & filename(1), imageName, 70)
End If
End Sub
Screenshot