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



41 comments:

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

    ReplyDelete
  2. This saved my life; thank you!

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

    ReplyDelete
  4. awesome work, saved me tons of time!

    ReplyDelete
  5. 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?

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

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

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

    ReplyDelete
  9. Excellent... you saved me :)

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

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

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

    ReplyDelete
  13. this tutorials is nice nice nice..

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

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

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

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

    ReplyDelete
  18. 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!

    ReplyDelete
  19. gr8 stuff
    thanks for sharing your knowledge

    http://soft-engineering.blogspot.com

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

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

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

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

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

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

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

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

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

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

    ReplyDelete
  30. @above: What error you are getting ?

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

    ReplyDelete
  32. Thanks was really helpful

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

    Thanks buddy!

    -Rakesh

    ReplyDelete