How to Crop an Image in C#

Abdullahi Salawudeen Feb 02, 2024
  1. Use the Graphics.DrawImage() Method to Draw and Crop an Image in C#
  2. Use DrawImage() With Five Parameters to Crop an Image in C#
  3. Use DrawImage() With Specified Portion, Location, and Size to Crop an Image in C#
How to Crop an Image in C#

This article will introduce how to draw and crop a specific image at a specified location with the original size using a C# code.

Use the Graphics.DrawImage() Method to Draw and Crop an Image in C#

Graphics can be found in the System.Drawing namespace and are primarily used to display or draw graphics or images in .Net-based Windows Applications. .Net provides multiple classes to deal with graphics objects and shapes such as pens, brushes, rectangles, circles, etc.

The Graphics and Image .Net classes can render an image on a Windows Form. The DrawImage() function draws a portion of an image at a specified location.

Below is a code snippet for the DrawImage function.

public void DrawImage(System.Drawing.Image image, float x, float y,
                      System.Drawing.RectangleF srcRect, System.Drawing.GraphicsUnit srcUnit);

The parameters are explained below:

  • image - specifies the image to draw.
  • x - specifies the x-coordinate of the image.
  • y - specifies the y-coordinate of the image.
  • srcRect - a RectangleF structure that specifies the portion of the image to draw.
  • srcUnit - a member of the GraphicsUnit enumeration that specifies the units of measure used by srcRect.

The following code example is implemented using Windows Forms and the Paint event handler with PaintEventArgs e as a parameter.

Below are the enumerated actions performed:

  1. An image was created from a JPEG file Koala.jpg located in the folder C:\Users\lolaa\Downloads.
  2. The coordinates to draw the image were created.
  3. A source rectangle was created to extract a portion of the image.
  4. The unit of measure was set to pixels.
  5. The image was drawn to the screen.

The specified source rectangle size determined the portion of the original unscaled image drawn on the screen.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CreatingImageObject {
  public partial class Form1 : Form {
    Image img = null;
    public Form1() {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e) {}

    private void button1_Click(object sender, EventArgs e) {
      if (img == null) {
        img = Image.FromFile(@"C:\Users\lolaa\Downloads\Koala.jpg");
      }
    }

    private void Form1_Paint(object sender, PaintEventArgs e) {
      if (img != null) {
        // Graphics g = e.Graphics;
        Graphics g = this.CreateGraphics();
        g.DrawImage(img, 0, 0, this.Width, this.Height);

        g.Dispose();
      }
    }
  }
}

Output:

Landing Page of the Application

When you click on the button, the image below is displayed:

Output:

Image - Koala Drawn on the Screen

Rectangle cropRect = new Rectangle(...);
Bitmap src = Image.FromFile(fileName) as Bitmap;
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);

using (Graphics g = Graphics.FromImage(target)) {
  g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel);
}

Use DrawImage() With Five Parameters to Crop an Image in C#

To edit or crop the image we drew earlier, we can use the DrawImage(Image, Single, Single, RectangleF, GraphicsUnit) function. You can see here that we used five parameters inside the function.

Updating the above code would give a different output. Below is the updated code example.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CreatingImageObject {
  public partial class Form1 : Form {
    Image img = null;
    public Form1() {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e) {}

    private void button1_Click(object sender, EventArgs e) {
      if (img == null) {
        // Create image.
        img = Image.FromFile(@"C:\Users\lolaa\Downloads\Koala.jpg");
      }
    }

    private void Form1_Paint(object sender, PaintEventArgs e) {
      if (img != null) {
        Graphics g = this.CreateGraphics();

        // specify the coordinates for upper-left corner of image.
        float x = 100.0F;
        float y = 100.0F;

        // rectangle is created for the source image with custom dimensions.
        RectangleF srcRect = new RectangleF(50.0F, 50.0F, 150.0F, 150.0F);
        GraphicsUnit dim = GraphicsUnit.Pixel;

        // image is drawn to the screen.
        g.DrawImage(img, x, y, srcRect, dim);
        g.Dispose();
      }
    }
  }
}

Output:

Image - Cropped Image of Koala

Use DrawImage() With Specified Portion, Location, and Size to Crop an Image in C#

We can also use the DrawImage() function to draw a specified portion of the selected image at the specified location and with the specified size.

Syntax:

public void DrawImage(System.Drawing.Image image, System.Drawing.Rectangle destRect, float srcX,
                      float srcY, float srcWidth, float srcHeight,
                      System.Drawing.GraphicsUnit srcUnit,
                      System.Drawing.Imaging.ImageAttributes? imageAttrs,
                      System.Drawing.Graphics.DrawImageAbort? callback, IntPtr callbackData);

Updating the above code would give a different output. Below is the updated code example.

The parameters are explained below:

  • image - specifies the image to draw.
  • destRect - specifies the location and size of the image on the screen. It scales the drawn image to fit the rectangle.
  • srcX and srcY - the x- and y-coordinates of the upper-left corner of the image.
  • srcWidth and srcHeight - specify the width and height of the image, respectively.
  • srcUnit - belongs to the GraphicsUnit enumeration. It is the units of measurement used by the srcRect parameter.
  • imageAttrs - an ImageAttributes instance that specifies recoloring and gamma information for image objects.
  • callback - a delegate function of the Graphics.DrawImageAbort. It specifies the DrawImage() overload to call when drawing the image. The application’s specification determines the number of times this method will be called.
  • callbackData - a value specifies additional data for the Graphics.DrawImageAbort delegate to use when checking whether to stop the execution of the DrawImage method.

The example of code below was also implemented using Windows Forms and the Paint event handler with PaintEventArgs e as a parameter.

The code performs the following actions:

  1. An instance of the Graphics.DrawImageAbort call-back method was created.
  2. A Koala.jpg image located in folder C:\Users\lolaa\Downloads was created.
  3. Points were created for the destination rectangle to draw the image.
  4. A rectangle container was created to specify the portion of the image to draw.
  5. The graphics drawing unit was set to pixel.
  6. The original image was drawn to the screen.
  7. An additional rectangle container to draw an adjusted image.
  8. Sets the attributes of the adjusted image to a larger gamma value.
  9. The adjusted image was drawn to the screen.

The Graphics.DrawImageAbort call-back returns a bool which determines the execution of the DrawImage method.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CreatingImageObject {
  public partial class Form1 : Form {
    Image img = null;
    public Form1() {
      InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e) {}

    // Define DrawImageAbort callback method.
    private bool DrawImageCallback8(IntPtr callBackData) {
      // Test for call that passes callBackData parameter.
      if (callBackData == IntPtr.Zero) {
        // If no callBackData passed, abort the DrawImage method.
        return true;
      } else {
        // If callBackData passed, continue DrawImage method.
        return false;
      }
    }
    private void button1_Click(object sender, EventArgs e) {
      if (img == null) {
        // Create image.
        img = Image.FromFile(@"C:\Users\lolaa\Downloads\Koala.jpg");
      }
    }

    private void Form1_Paint(object sender, PaintEventArgs e) {
      if (img != null) {
        Graphics g = this.CreateGraphics();

        // Create a call-back method.
        Graphics.DrawImageAbort imageCallback = new Graphics.DrawImageAbort(DrawImageCallback8);
        IntPtr imageCallbackData = new IntPtr(1);

        // Create image.
        // Image newImage = Image.FromFile(@"C:\Users\lolaa\Downloads\Koala.jpg");
        // img = Image.FromFile(@"C:\Users\lolaa\Downloads\Koala.jpg");

        // rectangle for the original image.
        Rectangle destRectOriginal = new Rectangle(100, 25, 450, 150);

        // coordinates of the rectangle.
        float x = 50.0F;
        float y = 50.0F;
        float width = 150.0F;
        float height = 150.0F;
        GraphicsUnit dim = GraphicsUnit.Pixel;

        // Draw original image to screen.
        g.DrawImage(img, destRectOriginal, x, y, width, height, dim);

        // rectangle for the adjusted image.
        Rectangle destRectAdjusted = new Rectangle(100, 175, 450, 150);

        // image attributes and sets gamma.
        ImageAttributes imageAttribute = new ImageAttributes();
        imageAttribute.SetGamma(4.0F);

        // Draw adjusted image to screen.
        try {
          checked {
            // Draw adjusted image to screen.
            g.DrawImage(img, destRectAdjusted, x, y, width, height, dim, imageAttribute,
                        imageCallback, imageCallbackData);
          }
        } catch (Exception ex) {
          g.DrawString(ex.ToString(), new Font("Arial", 8), Brushes.Black, new PointF(0, 0));
        }
      }
    }
    public void DrawImageRect4FloatAttribAbortData(PaintEventArgs e) {}
  }
}

Output:

Image - Original and Edited Image of Koala

Further discussion on other overloaded DrawImage() methods is available in this reference.

Abdullahi Salawudeen avatar Abdullahi Salawudeen avatar

Abdullahi is a full-stack developer and technical writer with over 5 years of experience designing and implementing enterprise applications. He loves taking on new challenges and believes conceptual programming theories should be implemented in reality.

LinkedIn GitHub

Related Article - Csharp Image