简体   繁体   English

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

[英]Crop image to certain ratio from virtual path c#

I would like to Crop an image to a ratio of 5/3.5 when I have the following: 当我满足以下条件时,我想将图像裁剪为5 / 3.5的比例:

  • Virtual path to image (~/Uploads/Images) 图像的虚拟路径(〜/上传/图像)
  • X Point for Top left corner of image 图像左上角的X点
  • Y Point for Top left corner of image 图像左上角的Y点
  • Image width 影像宽度
  • Image Height 影像高度

Here is an image showing what I mean: 这是一张图片,显示我的意思:

种植

The highlighted bits are what I have. 突出显示的位是我所拥有的。

How can I achieve that with C# in my MVC Controller? 如何在MVC控制器中使用C#实现该目标? I'd like to also store the image back to its original location, overwriting the old image if possible. 我还想将图像存储回其原始位置,并尽可能覆盖旧图像。

You can still use System.Drawing in asp.net even though its not recommended. 即使不建议在asp.net中使用System.Drawing

from what i understod you need a function with the following signiture 根据我的理解,您需要具有以下签名的功能

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

The task is fairly simple 任务很简单

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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM