Resize Image Before/And Upload To Databse ASP.NET

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.

Resize Image And Upload To SqlServer Databse In ASP.NET


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
01using System;
02using System.Data;
03using System.Configuration;
04using System.Web;
05using System.Web.Security;
06using System.Web.UI;
07using System.Web.UI.WebControls;
08using System.Web.UI.WebControls.WebParts;
09using System.Web.UI.HtmlControls;
10using System.IO;
11using System.Data.SqlClient;
12using System.Drawing.Imaging;
13using System.Drawing.Drawing2D;
14using System.Drawing;
15 
16 
17public partial class _Default : System.Web.UI.Page
18{
19    protected void Page_Load(object sender, EventArgs e)
20    {
21 
22    }
23protected 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
01Imports System
02Imports System.Data
03Imports System.Configuration
04Imports System.Web
05Imports System.Web.Security
06Imports System.Web.UI
07Imports System.Web.UI.WebControls
08Imports System.Web.UI.WebControls.WebParts
09Imports System.Web.UI.HtmlControls
10Imports System.IO
11Imports System.Data.SqlClient
12Imports System.Drawing.Imaging
13Imports System.Drawing.Drawing2D
14Imports System.Drawing
15 
16 
17Public 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
78End Class
Hope this helps

Download sample code attached



If you like this post than join us or share

41 comments:

siemens servis said... 1

thank you.


Umair Tahir said... 2

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


Anonymous said... 3

This saved my life; thank you!


J. Ibanez said... 4

This should work


my_images said... 5

This is what I have been definitely looking for. I'm using exactly C# and Vb.NET. Nice info, useful guidance... thanks a lot.


Unknown said... 6

awesome work, saved me tons of time!


Anonymous said... 7

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?


louis said... 8

This is the best thing for me! I also want to create a frame wall, which can lead my memory, in my home.


rahul said... 9

hello i have a problem
i want to modify menu item at run time using jquery


Anonymous said... 10

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....


Anonymous said... 11

Excellent... you saved me :)


Cost of Loadrunner said... 12

thanks, I have face lot of problem but now i am thankful to you for your post


asp.net web programming said... 13

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.


custom web design said... 14

testing at my end...will confirm after it :)


rulo çim said... 15

this tutorials is nice nice nice..


asp dot net developers said... 16

Pretty helpful. It really works great and also make application faster.


seo services said... 17

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.


Anonymous said... 18

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


asp net programmer said... 19

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.


Anonymous said... 20

Thanks!


Melinda said... 21

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!


ASP.NET C#.NET MSSQL WEBDESIGN Articles Tutorials said... 22

nice post


Anee said... 23

good technique


Anonymous said... 24

gr8 stuff
thanks for sharing your knowledge

http://soft-engineering.blogspot.com


asp-blogger said... 25

"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.


Anonymous said... 26

The link to the sample code download is pointing to the wrong file (gmailcontacts.zip)...plz fix it.


FixItPlease said... 27

The download-link to the sample code isn't working; it's pointing to the wrong file (gmailcontacts.zip).


jenifa said... 28

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.


Unknown said... 29

@Above: Thanks a lot for spotting, link is fixed -:))


ECommerce Web Development said... 30

Thanks for sharing the widget here, I will make sure to implement this method on my blog, I have bookmarked this blog,..


Property Management Software said... 31

I am a developer working in both ASP and C# , really a good sharing and very well explain , thanks for it.


Anonymous said... 32

hi zaffats


web hosting jaipur said... 33

Wow it is amazing posting. It is very helpful for my site. Thanks a Lot!


online marketing said... 34

I liked it so much, I can easily make change the size of the image originally. I hope this work for me.


Seo Company India said... 35

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.


Unknown said... 36

@above: What error you are getting ?


logo design contest said... 37

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.


Anonymous said... 38

Thanks was really helpful


R A N J A N said... 39

The best artile I have seen, I am using this and its working.

Thanks buddy!

-Rakesh


Anonymous said... 40

thnk


Anonymous said... 41

Thanks!


Find More Articles