2013-03-22

Crop an image when uploading to the server in ASP.NET

To crop an image when saving it to the server through asp:FileUpload control, we can use the below code. Here I’m using the Clone method of the Bitmap class and I’ve specified my area from the Rectangle. It actually creates a copy of the image within the specified area by the Rectangle.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            int x, y, width, height;
            x = y = 0; //X, Y values for crop the image.
            width = 300;
            height = 300;

            Rectangle cropArea = new Rectangle(x, y, width, height);

            Bitmap bmpImage = new Bitmap(FileUpload1.PostedFile.InputStream);
            Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
            bmpCrop.Save(@"D:\test.jpg");
        }
    }
}

Since we are using Rectangle and Bitmap classes, we have to import the System.Drawing namespace. Here I’m defining the width and height as 300px and X, Y value to 0. So it will crop 300x300 area from the image from the top left corner. Following is the markup I’ve used

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button"
    onclick="Button1_Click" />

Following is an example image file I’ve uploaded:

1

After upload it and being cropped, following is the result file uploaded to the server.

test

No comments: