.NET Core or .NET5 crop images according to coordinates

.NET Core or .NET5 crop the picture according to the upper left corner coordinates

Need to install System.Drawing.Common in nuget

using System;
using System.Drawing;


namespace ConsoleApp_imgcat
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //System.Drawing.Common   
            try
            {
    
    
                //方式一          
                //输入待裁剪原图
                Bitmap source = new Bitmap(@"D:\壁纸\5d1c6f42117cc.jpg");
                RectangleF rectangleF = new RectangleF(423, 576, 400, 400);            
                var newBitmap = source.Clone(rectangleF, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
                //保存裁剪的图片
                newBitmap.Save(@$"d:\壁纸\5d1c6f42117cc_4.jpg");
                newBitmap.Dispose();
                source.Dispose();

                //方式二
                Bitmap outImg = new Bitmap(400, 400);
                Graphics g = Graphics.FromImage(outImg);
                //输入待裁剪原图
                Bitmap inputImg = new Bitmap(@"d:\壁纸\5d1c6f42117cc.jpg");
                //x=-764,y=-156,这里要设置为负值,开始截图的左上角坐标
                g.DrawImage(inputImg, -423, -576);
                //保存裁剪的图片
                outImg.Save(@"d:\壁纸\5d1c6f42117cc_5.jpg");
                g.Dispose();
                outImg.Dispose();
                inputImg.Dispose();
            }
            catch (Exception ex)
            {
    
    
                string msg = ex.Message;
                Console.WriteLine("异常:" + msg);
            }
            Console.WriteLine("Hello World!");
            //Console.ReadKey();
        }
    }
}


Guess you like

Origin blog.csdn.net/u011511086/article/details/113337324