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
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;


public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
protected void btnUpload_Click(object sender, EventArgs e)
{
 string strImageName = txtName.Text.ToString();
 if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
 {
    string strExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
    if ((strExtension.ToUpper() == ".JPG") | (strExtension.ToUpper() == ".GIF"))
    {
     // Resize Image Before Uploading to DataBase
      System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
      int imageHeight = imageToBeResized.Height;
      int imageWidth = imageToBeResized.Width;
      int maxHeight = 240;
      int maxWidth = 320;
      imageHeight = (imageHeight * maxWidth) / imageWidth;
      imageWidth = maxWidth;

              if (imageHeight > maxHeight)
                {
                    imageWidth = (imageWidth * maxHeight) / imageHeight;
                    imageHeight = maxHeight;
                }

                Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
                System.IO.MemoryStream stream = new MemoryStream();
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                stream.Position = 0;
                byte[] image = new byte[stream.Length + 1];
                stream.Read(image, 0, image.Length);



                // Create SQL Connection 
                SqlConnection con = new SqlConnection();
                con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

                // Create SQL Command 

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;

                SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
                ImageName.Value = strImageName.ToString();
                cmd.Parameters.Add(ImageName);

                SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, image.Length);
                UploadedImage.Value = image;
                cmd.Parameters.Add(UploadedImage);
                con.Open();
                int result = cmd.ExecuteNonQuery();
                con.Close();
                if (result > 0)
                    lblMessage.Text = "File Uploaded";
                GridView1.DataBind();
            }
        }
    }
}


VB.NET
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Data.SqlClient
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D
Imports System.Drawing


Public Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        
    End Sub
    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim strImageName As String = txtName.Text.ToString()
        If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName <> "" Then
            Dim strExtension As String = System.IO.Path.GetExtension(FileUpload1.FileName)
            If (strExtension.ToUpper() = ".JPG") Or (strExtension.ToUpper() = ".GIF") Then
                ' Resize Image Before Uploading to DataBase
                Dim imageToBeResized As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
                Dim imageHeight As Integer = imageToBeResized.Height
                Dim imageWidth As Integer = imageToBeResized.Width
                Dim maxHeight As Integer = 240
                Dim maxWidth As Integer = 320
                imageHeight = (imageHeight * maxWidth) / imageWidth
                imageWidth = maxWidth
                
                If imageHeight > maxHeight Then
                    imageWidth = (imageWidth * maxHeight) / imageHeight
                    imageHeight = maxHeight
                End If
                
                Dim bitmap As New Bitmap(imageToBeResized, imageWidth, imageHeight)
                Dim stream As System.IO.MemoryStream = New MemoryStream()
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
                stream.Position = 0
                Dim image As Byte() = New Byte(stream.Length) {}
                stream.Read(image, 0, image.Length)
                
                
                
                ' Create SQL Connection 
                Dim con As New SqlConnection()
                con.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
                
                ' Create SQL Command 
                
                Dim cmd As New SqlCommand()
                cmd.CommandText = "INSERT INTO Images(ImageName,Image) VALUES (@ImageName,@Image)"
                cmd.CommandType = CommandType.Text
                cmd.Connection = con
                
                Dim ImageName As New SqlParameter("@ImageName", SqlDbType.VarChar, 50)
                ImageName.Value = strImageName.ToString()
                cmd.Parameters.Add(ImageName)
                
                Dim UploadedImage As New SqlParameter("@Image", SqlDbType.Image, image.Length)
                UploadedImage.Value = image
                cmd.Parameters.Add(UploadedImage)
                con.Open()
                Dim result As Integer = cmd.ExecuteNonQuery()
                con.Close()
                If result > 0 Then
                    lblMessage.Text = "File Uploaded"
                End If
                GridView1.DataBind()
            End If
        End If
    End Sub
End Class
Hope this helps

Download sample code attached



If you like this post than join us or share

41 comments:

siemens servis said...

thank you.


Umair Tahir said...

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

This saved my life; thank you!


J. Ibanez said...

This should work


my_images said...

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

awesome work, saved me tons of time!


Anonymous said...

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

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

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


Anonymous said...

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

Excellent... you saved me :)


Cost of Loadrunner said...

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


asp.net web programming said...

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

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


rulo çim said...

this tutorials is nice nice nice..


asp dot net developers said...

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


seo services said...

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

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

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

Thanks!


Melinda said...

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

nice post


Anee said...

good technique


Anonymous said...

gr8 stuff
thanks for sharing your knowledge

http://soft-engineering.blogspot.com


asp-blogger said...

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

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


FixItPlease said...

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


jenifa said...

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

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


ECommerce Web Development said...

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

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


Anonymous said...

hi zaffats


web hosting jaipur said...

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


online marketing said...

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

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

@above: What error you are getting ?


logo design contest said...

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

Thanks was really helpful


R A N J A N said...

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

Thanks buddy!

-Rakesh


Anonymous said...

thnk


Anonymous said...

Thanks!


Find More Articles