SoFunction
Updated on 2025-03-07

C# implements the compression and crop operation example of image files

This article describes the compression and cropping operation methods of C# for image files, which are very practical in C# project development. Share it for your reference. The details are as follows:

Generally, when working on projects, the processing of images used to limit their size when uploading, which brings many inconveniences. After all, website operation and maintenance personnel may not necessarily process images, and often exceed the size limit. Even if they use image processing software, the processing effect will be unsatisfactory due to personal level.

Therefore, the image editing function provided by C# is used to achieve one-stop uploading and generate target images of required sizes and sizes through the program.

The specific steps are as follows:

Let’s talk about image compression first:

Step 1: You need to read an image file, read method:

// <param name="ImageFilePathAndName">Full path name of image file</param>public Image ResourceImage =(ImageFilePathAndName); 

illustrate:

Image class: an abstract base class that references from, providing functionality for classes derived from Bitmap and Metafile.

Main properties: Size-> Gets the width and height of this image in pixels.

PhysicalDimension-> Gets the width and height of this image (if the image is a bitmap, returns the width and height in pixels. If the image is a metafile, returns the width and height in 0.01 mm.).

PixelFormat->Get the pixel format of this Image.

Height, Width->Get the height and width of this Image (in pixels).

Main method: FromFile(String)->Create Image from the specified file.

FromStream(Stream)->Create Image from the specified data stream.

Save(String fileName)->Save this Image to the specified file or stream.

Save(Stream, ImageFormat)->Save this image in the specified format to the specified stream.

Save(String, ImageFormat)->Save this Image in the specified format to the specified file.

For more attributes and method descriptions, please click.

The second step is to generate a thumbnail image and draw the original image content to the target image according to the specified size.

/// &lt;summary&gt; 
/// Generate thumbnail overload method 1, return the image object of the thumbnail/// &lt;/summary&gt; 
/// <param name="Width">Thread of thumbnail</param>/// <param name="Height">Height of thumbnail</param>/// <returns> Image object for thumbnail</returns>public Image GetReducedImage(int Width, int Height) 
{ 
  try 
  { 
 //Initialize a new instance of Bitmap class with the specified size and format Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); 
 //Create a new Graphics object from the specified Image object Graphics graphics = (bitmap); 
 //Clear the entire drawing surface and fill it with transparent background color (); 
 //Draw the original image object at the specified position and according to the specified size (ResourceImage, new Rectangle(0, 0, Width, Height)); 
 return bitmap; 
  } 
  catch (Exception e) 
  { 
 ErrMessage = ; 
 return null; 
  } 
} 

illustrate:

1. Bitmap class

Referenced from, encapsulated GDI+ bitmap, which consists of pixel data of graphic images and their characteristics. Bitmap is an object used to process images defined by pixel data.

For detailed introduction to objects that encapsulate images, please refer to the official documentation:/zh-cn/library/

2. Graphics

Referenced from, (the object that processes the image), encapsulates a GDI+ drawing surface.

For Graphics, click here to view the official tutorial:/zh-cn/library/

Step 3: Save

The Image object returned in the second step is temporarily named: iImage:

(pathAndName, ); 

The above is the compression operation. After the test, the 101k picture is 57k after compression. This should have something to do with the size.

The following is the picture cropping. In fact, the principle is similar to the above, and it is nothing more than repainting the picture.

/// &lt;summary&gt; 
/// How to capture images/// &lt;/summary&gt; 
/// <param name="url">Picture address</param>/// <param name="beginX">Start position-X</param>/// <param name="beginY">Start position-Y</param>/// <param name="getX">Intercept width</param>/// <param name="getY">Intercept the length</param>/// <param name="fileName">File name</param>/// <param name="savePath">SavePath</param>/// <param name="fileExt">Suffix name</param>public static string CutImage(string url, int beginX, int beginY, int getX, int getY, string fileName, string savePath, string fileExt) 
{ 
  if ((beginX &lt; getX) &amp;&amp; (beginY &lt; getY)) 
  { 
 Bitmap bitmap = new Bitmap(url);//Original pictureif (((beginX + getX) &lt;= ) &amp;&amp; ((beginY + getY) &lt;= )) 
 { 
   Bitmap destBitmap = new Bitmap(getX, getY);//Target map   Rectangle destRect = new Rectangle(0, 0, getX, getY);//Rectangular container   Rectangle srcRect = new Rectangle(beginX, beginY, getX, getY); 

   (destBitmap); 
(bitmap, destRect, srcRect, ); 
    
   ImageFormat format = ; 
   switch (()) 
   { 
 case "png": 
   format = ; 
   break; 
 case "bmp": 
   format = ; 
   break; 
 case "gif": 
   format = ; 
   break; 
   } 
   (savePath + "//" + fileName , format); 
   return savePath + "\\" + "*" + ('.')[0] + "." + fileExt; 
 } 
 else 
 { 
   return "The intercept range exceeds the image range"; 
 } 
  } 
  else 
  { 
 return "Please confirm(beginX &lt; getX)&amp;&amp;(beginY &lt; getY)"; 
  } 
} 

illustrate:

Rectangle class: rectangle, please refer to the official document for details:/zh-cn/library/(v=vs.85).aspx

The above is the sample code for cropping an image file.

The code used in this article is the real code in the project and has been tested.

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