Resize Image Before/And Upload To SqlServer Databse In ASP.NET 2.0,3.5,4.0 Using C# VB.NET. For this i am using FileUpload control to upload the image in datbase after resizing, and displaying Images in Gridview.

HTML SOURCE OF PAGE
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
<asp:Button ID="btnUpload" runat="server"
OnClick="btnUpload_Click" Text="Upload" />
<br />
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"
InsertVisible="False" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName"
SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [ImageName], [Image]
FROM [Images]"></asp:SqlDataSource>
</div>
</form>
C# CODE
01
using
System;
02
using
System.Data;
03
using
System.Configuration;
04
using
System.Web;
05
using
System.Web.Security;
06
using
System.Web.UI;
07
using
System.Web.UI.WebControls;
08
using
System.Web.UI.WebControls.WebParts;
09
using
System.Web.UI.HtmlControls;
10
using
System.IO;
11
using
System.Data.SqlClient;
12
using
System.Drawing.Imaging;
13
using
System.Drawing.Drawing2D;
14
using
System.Drawing;
15
16
17
public
partial
class
_Default : System.Web.UI.Page
18
{
19
protected
void
Page_Load(
object
sender, EventArgs e)
20
{
21
22
}
23
protected
void
btnUpload_Click(
object
sender, EventArgs e)
24
{
25
string
strImageName = txtName.Text.ToString();
26
if
(FileUpload1.PostedFile !=
null
&& FileUpload1.PostedFile.FileName !=
""
)
27
{
28
string
strExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
29
if
((strExtension.ToUpper() ==
".JPG"
) | (strExtension.ToUpper() ==
".GIF"
))
30
{
31
// Resize Image Before Uploading to DataBase
32
System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
33
int
imageHeight = imageToBeResized.Height;
34
int
imageWidth = imageToBeResized.Width;
35
int
maxHeight = 240;
36
int
maxWidth = 320;
37
imageHeight = (imageHeight * maxWidth) / imageWidth;
38
imageWidth = maxWidth;
39
40
if
(imageHeight > maxHeight)
41
{
42
imageWidth = (imageWidth * maxHeight) / imageHeight;
43
imageHeight = maxHeight;
44
}
45
46
Bitmap bitmap =
new
Bitmap(imageToBeResized, imageWidth, imageHeight);
47
System.IO.MemoryStream stream =
new
MemoryStream();
48
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
49
stream.Position = 0;
50
byte
[] image =
new
byte
[stream.Length + 1];
51
stream.Read(image, 0, image.Length);
52
53
54
55
// Create SQL Connection
56
SqlConnection con =
new
SqlConnection();
57
con.ConnectionString = ConfigurationManager.ConnectionStrings[
"ConnectionString"
].ConnectionString;
58
59
// Create SQL Command
60
61
SqlCommand cmd =
new
SqlCommand();
62
cmd.CommandText =
"INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)"
;
63
cmd.CommandType = CommandType.Text;
64
cmd.Connection = con;
65
66
SqlParameter ImageName =
new
SqlParameter(
"@ImageName"
, SqlDbType.VarChar, 50);
67
ImageName.Value = strImageName.ToString();
68
cmd.Parameters.Add(ImageName);
69
70
SqlParameter UploadedImage =
new
SqlParameter(
"@Image"
, SqlDbType.Image, image.Length);
71
UploadedImage.Value = image;
72
cmd.Parameters.Add(UploadedImage);
73
con.Open();
74
int
result = cmd.ExecuteNonQuery();
75
con.Close();
76
if
(result > 0)
77
lblMessage.Text =
"File Uploaded"
;
78
GridView1.DataBind();
79
}
80
}
81
}
82
}
VB.NET
01
Imports
System
02
Imports
System.Data
03
Imports
System.Configuration
04
Imports
System.Web
05
Imports
System.Web.Security
06
Imports
System.Web.UI
07
Imports
System.Web.UI.WebControls
08
Imports
System.Web.UI.WebControls.WebParts
09
Imports
System.Web.UI.HtmlControls
10
Imports
System.IO
11
Imports
System.Data.SqlClient
12
Imports
System.Drawing.Imaging
13
Imports
System.Drawing.Drawing2D
14
Imports
System.Drawing
15
16
17
Public
Partial
Class
_Default
18
Inherits
System.Web.UI.Page
19
Protected
Sub
Page_Load(
ByVal
sender
As
Object
,
ByVal
e
As
EventArgs)
20
21
End
Sub
22
Protected
Sub
btnUpload_Click(
ByVal
sender
As
Object
,
ByVal
e
As
EventArgs)
23
Dim
strImageName
As
String
= txtName.Text.ToString()
24
If
FileUpload1.PostedFile IsNot
Nothing
AndAlso
FileUpload1.PostedFile.FileName <>
""
Then
25
Dim
strExtension
As
String
= System.IO.Path.GetExtension(FileUpload1.FileName)
26
If
(strExtension.ToUpper() =
".JPG"
)
Or
(strExtension.ToUpper() =
".GIF"
)
Then
27
' Resize Image Before Uploading to DataBase
28
Dim
imageToBeResized
As
System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
29
Dim
imageHeight
As
Integer
= imageToBeResized.Height
30
Dim
imageWidth
As
Integer
= imageToBeResized.Width
31
Dim
maxHeight
As
Integer
= 240
32
Dim
maxWidth
As
Integer
= 320
33
imageHeight = (imageHeight * maxWidth) / imageWidth
34
imageWidth = maxWidth
35
36
If
imageHeight > maxHeight
Then
37
imageWidth = (imageWidth * maxHeight) / imageHeight
38
imageHeight = maxHeight
39
End
If
40
41
Dim
bitmap
As
New
Bitmap(imageToBeResized, imageWidth, imageHeight)
42
Dim
stream
As
System.IO.MemoryStream =
New
MemoryStream()
43
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
44
stream.Position = 0
45
Dim
image
As
Byte
() =
New
Byte
(stream.Length) {}
46
stream.Read(image, 0, image.Length)
47
48
49
50
' Create SQL Connection
51
Dim
con
As
New
SqlConnection()
52
con.ConnectionString = ConfigurationManager.ConnectionStrings(
"ConnectionString"
).ConnectionString
53
54
' Create SQL Command
55
56
Dim
cmd
As
New
SqlCommand()
57
cmd.CommandText =
"INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)"
58
cmd.CommandType = CommandType.Text
59
cmd.Connection = con
60
61
Dim
ImageName
As
New
SqlParameter(
"@ImageName"
, SqlDbType.VarChar, 50)
62
ImageName.Value = strImageName.ToString()
63
cmd.Parameters.Add(ImageName)
64
65
Dim
UploadedImage
As
New
SqlParameter(
"@Image"
, SqlDbType.Image, image.Length)
66
UploadedImage.Value = image
67
cmd.Parameters.Add(UploadedImage)
68
con.Open()
69
Dim
result
As
Integer
= cmd.ExecuteNonQuery()
70
con.Close()
71
If
result > 0
Then
72
lblMessage.Text =
"File Uploaded"
73
End
If
74
GridView1.DataBind()
75
End
If
76
End
If
77
End
Sub
78
End
Class
Download sample code attached
If you like this post than join us or share
41 comments:
thank you.
After this post , I can easily make change the size of the image originally. Because Image consist of a bit of streams and can be managed by powerful classes given by the Asp.net
Nice Information!
Regards
Custom Web design
This saved my life; thank you!
This should work
This is what I have been definitely looking for. I'm using exactly C# and Vb.NET. Nice info, useful guidance... thanks a lot.
awesome work, saved me tons of time!
FileUpload1.PostedFile.SaveAs(Server.MapPath("UyeProfilResimleri/"+ image));
I don't store the image at database. I store only the name of it. The file is in a folder in my project.
After resizing, I can't save the resized new image into my folder.
Can you help me?
This is the best thing for me! I also want to create a frame wall, which can lead my memory, in my home.
hello i have a problem
i want to modify menu item at run time using jquery
hi
thnks a lot for good code....
but i have a daudt . if we upload gif images , then in the database it is changed totally..cant we resize gif image without changing....
Excellent... you saved me :)
thanks, I have face lot of problem but now i am thankful to you for your post
I was surfing for this solution from so long and I was just about to loose the hope for getting the solution. Thanks a ton finally my surf ends with fruitful result. I hope this work for me.
testing at my end...will confirm after it :)
this tutorials is nice nice nice..
Pretty helpful. It really works great and also make application faster.
I liked it very much, after reading this post anyone can easily change the size of image and attach or upload to the asp.net database.
Thanks.
Hi,
I have an error on the Default.aspx.cs page
Line:
int result = cmd.ExecuteNonQuery();
Error:
Cannot insert the value NULL into column 'ID', table 'Database.dbo.Images'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Please help Me
I came on your blog for the first and I have seen your work. I must say you have maintained your Blog really well. Good on you.
Thanks!
Is anyone else having a problem with the image not showing in the data grid? I'm only getting a red x. Very frustrated because I'm not seeing what I did wrong and I've re-done the code multiple times. Any help would be greatly appreciated if anyone else has had this issue.
Thanks!
nice post
good technique
gr8 stuff
thanks for sharing your knowledge
http://soft-engineering.blogspot.com
"Melinda said... 22
Is anyone else having a problem with the image not showing in the data grid? I'm only getting a red x. Very frustrated because I'm not seeing what I did wrong and I've re-done the code multiple times. Any help would be greatly appreciated if anyone else has had this issue.
Thanks!"
Melinda please check the imageurl . Image control cannot find any image in that location thats why its showing x mark.
The link to the sample code download is pointing to the wrong file (gmailcontacts.zip)...plz fix it.
The download-link to the sample code isn't working; it's pointing to the wrong file (gmailcontacts.zip).
hi
really a nice post..am new to this domain..I worked this with ms access..it is giving error while debugging as
keyword not supported:"provider"
Line 63:
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
plz help me to fix this error.
@Above: Thanks a lot for spotting, link is fixed -:))
Thanks for sharing the widget here, I will make sure to implement this method on my blog, I have bookmarked this blog,..
I am a developer working in both ASP and C# , really a good sharing and very well explain , thanks for it.
hi zaffats
Wow it is amazing posting. It is very helpful for my site. Thanks a Lot!
I liked it so much, I can easily make change the size of the image originally. I hope this work for me.
I did wrong and I've re-done the code multiple times. Any help would be greatly appreciated if anyone else has had this issue.
@above: What error you are getting ?
Well that's superb article! Thank you for this great information, you write very well which i like very much. I am really impressed by your post.
Thanks was really helpful
The best artile I have seen, I am using this and its working.
Thanks buddy!
-Rakesh
thnk
Thanks!
Post a Comment