SoFunction
Updated on 2025-04-05

C# picture scaling example

This article shares the specific code of scaled C# images for your reference. The specific content is as follows

Tool class code:

using System;
using ;
using ;
using .Drawing2D;
using ;
using ;
using ;
using ;

namespace 
{
 /// <summary>
 /// Image zoom /// </summary>
 public class ZoomImageUtil
 {
  /// <summary>
  /// Image zoom  /// </summary>
  /// <param name="bmp">Picture</param>  /// <param name="width">Target width, if it is 0, it means that the width is scaled proportionally</param>  /// <param name="height">Target length, if it is 0, it means that the length is scaled to scale</param>  public static Bitmap GetThumbnail(Bitmap bmp, int width, int height)
  {
   if (width == 0)
   {
    width = height *  / ;
   }
   if (height == 0)
   {
    height = width *  / ;
   }

   Image imgSource = bmp;
   Bitmap outBmp = new Bitmap(width, height);
   Graphics g = (outBmp);
   ();
   // Set the canvas' depiction quality    = ;
    = ;
    = ;
   (imgSource, new Rectangle(0, 0, width, height + 1), 0, 0, , , );
   ();
   ();
   ();
   return outBmp;
  }
 }
}

Example of usage:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

namespace ZoomImage
{
 public partial class Form1 : Form
 {
  public Form1()
  {
   InitializeComponent();
  }

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

  private void txtWidth_KeyPress(object sender, KeyPressEventArgs e)
  {
   if ( != 8 &amp;&amp; !())
   {
     = true;
   }
  }

  private void txtHeight_KeyPress(object sender, KeyPressEventArgs e)
  {
   if ( != 8 &amp;&amp; !())
   {
     = true;
   }
  }

  private void btnSelectImage_Click(object sender, EventArgs e)
  {
   try
   {
    if ( == "" &amp;&amp;  == "")
    {
     return;
    }

    if (() == )
    {
     (() =&gt;
     {
      string path = ([0]) + "\\NewImage\\";

      int i = 0;
      foreach (string fileName in )
      {
       Bitmap bmp = (new Bitmap(fileName), Convert.ToInt32( == "" ? "0" : ), Convert.ToInt32( == "" ? "0" : ));
       if (!(path))
       {
        (path);
       }
       (path + (fileName));
       (path + (fileName));
       (new InvokeDelegate(() =&gt;
       {
         = ("schedule:{1}/{0}", , ++i);
       }));
       (1);
      }

      ("success!");
     });
    }
   }
   catch (Exception ex)
   {
    ();
   }
  }

 }

 /// &lt;summary&gt;
 /// Delegate for cross-thread access control /// &lt;/summary&gt;
 public delegate void InvokeDelegate();
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.