Updated on Kisan Patel
This tutorial will explain you how to crop image using C# System.Drawing class in ASP.NET web application?
Here, we need to use Bitmap.Clone method as seen in below method to creates a copy of the section of this Bitmap defined by Rectangle structure and with a specified PixelFormat enumeration.
public static Image CropImage(Image img, Rectangle cropArea) { var bmpImage = new Bitmap(img); var bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat); return bmpCrop; }
So Lets First create New ASP.NET web application and add the below line of code to Default.aspx page.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebCropImage.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>ASP.NET Image Crop Demo</title> </head> <body> <form id="form1" runat="server"> <div> <p> <label>Select the file: </label> <asp:FileUpload ID="file_upload" runat="server" /> </p> <p> Height: <asp:TextBox ID="txt_Width" runat="server"></asp:TextBox> Width: <asp:TextBox ID="txt_Height" runat="server"></asp:TextBox> </p> <p> <asp:Button ID="btn_CropImage" runat="server" Text="Crop Now" OnClick="btn_CropImage_Click" /> </p> </div> </form> </body> </html>
Now, add the following code to default.aspx.cs class to crop the image using C# System.Drawing class.
using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using Image = System.Drawing.Image; namespace WebCropImage { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public static Image CropImage(Image img, Rectangle cropArea) { var bmpImage = new Bitmap(img); var bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat); return bmpCrop; } protected void btn_CropImage_Click(object sender, EventArgs e) { string filename = System.IO.Path.GetFileName(file_upload.FileName); file_upload.SaveAs(Server.MapPath("~/upload/") + filename); //Get the height and width of Crop image var w = Convert.ToInt32(txt_Width.Text); var h = Convert.ToInt32(txt_Height.Text); //Get the image using (var bitmap = Image.FromFile(Server.MapPath("~/upload/") + filename)) { var rectangle = new Rectangle(); //Set the position Centered to crop image from centered var value = "Centered"; switch (value.ToString()) { case "Centered": var x = ((bitmap.Width - w) / 2); var y = ((bitmap.Height - h) / 2); rectangle = new Rectangle(x, y, w, h); break; //Crop Image from TopLeft Corner default: rectangle = new Rectangle(0, 0, w, h); break; } using (var resized = CropImage(bitmap, rectangle)) { //Save image into memory stream... using (var ms = new MemoryStream()) { resized.Save(ms, ImageFormat.Jpeg); } //Save the cropped Image file to "cropped" folder... resized.Save(Server.MapPath("~/cropped/") + filename, ImageFormat.Jpeg); } } } } }