从虚拟路径 c# 将图像裁剪为一定比例

Crop image to certain ratio from virtual path c#

当我有以下条件时,我想将图像裁剪为 5/3.5 的比例:

这是一张显示我的意思的图片:

高亮部分是我的。

如何在我的 MVC 控制器中使用 C# 实现这一点?我还想将图像存储回其原始位置,如果可能的话覆盖旧图像。

尽管不推荐,您仍然可以在 asp.net 中使用 System.Drawing

据我了解,您需要具有以下签名的函数

public static void CropAndOverwrite(string imgPath,int x1, int y1, int height, int width)

任务相当简单

public static void CropAndOverwrite(string imgPath, int x1, int y1, int height, int width)
    {

        //Create a rectanagle to represent the cropping area
        Rectangle rect = new Rectangle(x1, y1, width, height);
        //see if path if relative, if so set it to the full path
        if (imgPath.StartsWith("~"))
        {
            //Server.MapPath will return the full path
            imgPath = Server.MapPath(imgPath);
        }
        //Load the original image
        Bitmap bMap = new Bitmap(imgPath);
        //The format of the target image which we will use as a parameter to the Save method
        var format = bMap.RawFormat;


        //Draw the cropped part to a new Bitmap
        var croppedImage = bMap.Clone(rect, bMap.PixelFormat);

        //Dispose the original image since we don't need it any more
        bMap.Dispose();

        //Remove the original image because the Save function will throw an exception and won't Overwrite by default
        if (System.IO.File.Exists(imgPath))
            System.IO.File.Delete(imgPath);

        //Save the result in the format of the original image
        croppedImage.Save(imgPath,format);
        //Dispose the result since we saved it
        croppedImage.Dispose();
    }