从虚拟路径c#裁剪图像到特定比例

时间:2015-03-25 13:12:54

标签: c# asp.net-mvc-5 crop jcrop

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

  • 图像的虚拟路径(〜/上传/图像)
  • 图像左上角的X点
  • 图像左上角的Y点
  • 图片宽度
  • 图像高度

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

cropping

突出显示的位是我的。

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

1 个答案:

答案 0 :(得分:1)

即使不推荐使用,也可以在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();
    }
相关问题