How to Upload and Crop File in Asp.Net

Description: File Upload Controls through we will Upload file and Using Crop method what we create in code behind through we will Cropped Uploaded File. When we Upload file that time we will Check File Extension, Size or etc. Using Panel through we will Maintain all Controls One by one in Lines in Webpage So we can Upload set Coords and Cropped file. For that we have Path where we have to set Uploaded image and after Cropped image in Folder it Could be on Server Side on Client Side. Here we will Store in Server Side. Using Cropped Method through  we will Cropped image Size and after return that image byte size to that Controls and save in Folder. So let’s Start and Create.

Step 1: Design your Webpage like below.

<div>
  <asp:Panel ID="pnlUpload" runat="server">
  <asp:FileUpload ID="Upload" runat="server" />
  <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
  </asp:Panel>
  <asp:Panel ID="pnlCrop" runat="server">
  <asp:Image ID="imgCrop" runat="server" Height="181px" Width="324px" />
  <br />
  </asp:Panel>
  <asp:Panel ID="XYPanel" runat="server">
  X:<asp:TextBox ID="txtx" runat="server" Height="20px" Width="74px"></asp:TextBox>
  &nbsp;&nbsp;&nbsp; Y:<asp:TextBox ID="txty" runat="server" Width="68px"></asp:TextBox>
  &nbsp;&nbsp;&nbsp;
<asp:Button ID="btnCrop"runat="server" Text="Crop" OnClick="btnCrop_Click"Width="81px" />
</asp:Panel>
<br />
<asp:Panel ID="pnlCropped" runat="server">
<asp:Image ID="imgCropped" runat="server" Height="194px" Width="327px" />
</asp:Panel>
<asp:Label ID="lblError" runat="server" Text=""></asp:Label>
</div>

In Page load event we will set visible false all panel without file upload panel and Set path for image Folder.

String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";
        String pathCroped = HttpContext.Current.Request.PhysicalApplicationPath + "images\\croped\\";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                pnlCrop.Visible = false;
                pnlCropped.Visible = false;
                XYPanel.Visible = false;
            }
        }

Now Code for Upload file and Check Extension, File Size etc on Upload button Click event.

protected void btnUpload_Click(object sender, EventArgs e)
        {
            Boolean FileOK = false;
            Boolean FileSaved = false;
            if (Upload.HasFile)
            {
                Session["UploadImage"] = Upload.FileName;
                String FileExtension = Path.GetExtension(Session["UploadImage"].ToString()).ToLower();
                String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (FileExtension == allowedExtensions[i])
                    {
                        FileOK = true;
                    }
                }
            }
            if (FileOK)
            {
                try
                {
                    Upload.PostedFile.SaveAs(path + Session["UploadImage"]);
                    FileSaved = true;
                }
                catch (Exception ex)
                {
                    lblError.Text = "File could not be uploaded." + ex.Message.ToString();
                    lblError.Visible = true;
                    FileSaved = false;
                }
            }
            else
            {
                lblError.Text = "Cannot accept files of this type.";
                lblError.Visible = true;
            }
            if (FileSaved)
            {
                pnlUpload.Visible = false;
                pnlCrop.Visible = true;
                XYPanel.Visible = true;
                imgCrop.ImageUrl = "images/" + Session["UploadImage"].ToString();
                txtx.Text = "0";
                txty.Text = "0";
            }
        }
Now On Crop button Click event Code for How to Cropped file and Save to Folder.

protected void btnCrop_Click(object sender, EventArgs e)
        {
            int x = Convert.ToInt32(txtx.Text);
            int y = Convert.ToInt32(txty.Text);
            if (x < 0 && y < 0)
            {
                lblError.ForeColor = System.Drawing.Color.Red;
                lblError.Text = "Enter Coords in X and Y Position";
            }
            else
            {
                string ImageName = Session["UploadImage"].ToString();
                byte[] CropImage = Crop(path + ImageName, 700, 600, x, y);
                using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
                {
                    ms.Write(CropImage, 0, CropImage.Length);
                    using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
                    {
                        string SaveTo = pathCroped + "croped_" + ImageName;
                        CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
                        pnlCrop.Visible = false;
                        XYPanel.Visible = false;
                        pnlCropped.Visible = true;
                        imgCropped.ImageUrl = "images/croped/" + "croped_" + ImageName;
                        lblError.Text = "";
                    }
                }
            }
        }

Now here is the Cropped Method 

static byte[] Crop(string Img, int Width, int Height, int X, int Y)
        {
            try
            {
                using (SD.Image OriginalImage = SD.Image.FromFile(Img))
                {
                    using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))
                    {
                        bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
                        using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
                        {
                            Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                            Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height), X, Y, Width, Height, SD.GraphicsUnit.Pixel);
                            MemoryStream ms = new MemoryStream();
                            bmp.Save(ms, OriginalImage.RawFormat);
                            return ms.GetBuffer();
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
        }

Now Check in your Browser and Upload File and Set Coords for Cropped Image.


Related Posts

Previous
Next Post »

Thanks for comments.....