The best way to Upload Image and resize it for gallery

Sometimes we need to use galleries in our sites such as light box or any JQuery photo gallery , But the gallery needs two separate image files . One is big and the other is small or thumbnail.
We don't need to bother the user for uploading 2 files with different sizes (width and height).
consider this example :

first of all create Uploading folder inside your root

aspx page
<asp:FileUpload ID="imageFile" runat="server" />
<asp:Button ID="btnFileUpload" runat="server" Text="Upload"
            onclick="btnFileUpload_Click" />

<asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>

C# code behind
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

public Bitmap ResizeBitmap(Bitmap src, int newWidth, int newHeight)
{
        Bitmap result = new Bitmap(newWidth, newHeight);
        using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
        {
            g.DrawImage(src, 0, 0, newWidth, newHeight);
        }
        return result;
}


protected void btnFileUpload_Click(object sender, EventArgs e)
{
        bool fileExist = false;
        if (imageFile.HasFile)
        {
            try
            {
                string fileName = imageFile.FileName;
                string location = Server.MapPath("./Uploading/") + fileName;
                if (!File.Exists(location))
                {
                    // Get the bitmap data from the uploaded file
                    Bitmap src = Bitmap.FromStream(imageFile.PostedFile.InputStream) as Bitmap;
                    // Resize the big Image
                    Bitmap bigResult = ResizeBitmap(src, 640, 480);
                    bigResult.Save(location, ImageFormat.Jpeg);

                    string smallFileName = "small_" + imageFile.FileName;
                    // Resize the small image
                    Bitmap smallResult = ResizeBitmap(src, 200, 150);
                    string smallLocation = Server.MapPath("./Uploading/") + smallFileName;
                    smallResult.Save(smallLocation, ImageFormat.Jpeg);
                }
                else
                {
                    fileExist = true;
                    this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",
"<script language='javascript'>alert('The file is exist !!! ');</script>");

                }
            }
            catch (Exception ex)
            {
                lblStatus.Text = "Upload status: The file could not be uploaded. The following error occured: " +     ex.Message;
            }
           
        }

       
}




0 comments:

Post a Comment