SoFunction
Updated on 2025-04-06

Example of C# method to achieve scaling and cropping pictures

This article describes the method of scaling and cropping images in C#. Share it for your reference, as follows:

using System;
using ;
using ;
using ;
using .Drawing2D;
using ;
namespace Project
{
  class ImageOperation
  {
    /// <summary>
    /// Resize picture    /// </summary>
    /// <param name="bmp">original Bitmap </param>    /// <param name="newW">New Width</param>    /// <param name="newH">New height</param>    /// <param name="Mode">Remain, not used yet</param>    /// <returns>Processing the pictures afterwards</returns>    public static Bitmap ResizeImage(Bitmap bmp, int newW, int newH, int Mode)
    {
      try
      {
        Bitmap b = new Bitmap(newW, newH);
        Graphics g = (b);
        // Quality of interpolation algorithm         = ;
        (bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, , ), );
        ();
        return b;
      }
      catch
      {
        return null;
      }
    }
    /// &lt;summary&gt;
    /// Clipping -- Use GDI+    /// &lt;/summary&gt;
    /// <param name="b">original Bitmap</param>    /// <param name="StartX">Start coordinate X</param>    /// <param name="StartY">Start coordinate Y</param>    /// <param name="iWidth">Width</param>    /// <param name="iHeight">Height</param>    /// <returns>Cropped Bitmap</returns>    public static Bitmap Cut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight)
    {
      if (b == null)
      {
        return null;
      }
      int w = ;
      int h = ;
      if (StartX &gt;= w || StartY &gt;= h)
      {
        return null;
      }
      if (StartX + iWidth &gt; w)
      {
        iWidth = w - StartX;
      }
      if (StartY + iHeight &gt; h)
      {
        iHeight = h - StartY;
      }
      try
      {
        Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
        Graphics g = (bmpOut);
        (b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), );
        ();
        return bmpOut;
      }
      catch
      {
        return null;
      }
    }
  }
}

The goals are actuallynew Rectangle(0, 0, iWidth, iHeight), the scaling algorithm plugs the entire original map into the target areanew Rectangle(0, 0, , ), and the cut is just to stuff the original area with a width and height area of ​​1:1 into the target area.

For more information about C#, please visit the special topic of this site:Summary of C# picture operation skills》、《Tutorial on the usage of common C# controls》、《Summary of WinForm control usage》、《C# data structure and algorithm tutorial》、《Introduction to C# object-oriented programming tutorial"and"Summary of thread usage techniques for C# programming

I hope this article will be helpful to everyone's C# programming.