【问题标题】:Crop image to certain ratio from virtual path c#从虚拟路径c#将图像裁剪为一定比例
【发布时间】:2015-05-29 04:25:37
【问题描述】:

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

  • 图像的虚拟路径(~/Uploads/Images)
  • 图像左上角的 X 点
  • 图像左上角的 Y 点
  • 图像宽度
  • 图像高度

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

突出显示的部分是我所拥有的。

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

【问题讨论】:

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


    【解决方案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();
        }
    

    【讨论】:

    • 感谢@decoherence。为什么不推荐System.Drawing
    • 谢谢,在这一行Image.FromFile(imgPath); 我收到一个错误,说它无法加载文件! imgPath~/uploads/images。我需要对路径做一些特别的事情吗?
    • @Ciwan 使用完整路径,路径必须指向单个图像c:/uploads/images/someImage.jpg 不确定~/uploads/images/someImage.jpg 是否有效,但您可以尝试
    • 感谢@decoherence。 Aye 刚刚做了一些谷歌搜索,结果发现.FromFile() 需要完整路径,否则它会在同一个目录中查找。知道如何从~/uploads/imagesx:/work/app/uploads/images/ 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2012-01-07
    相关资源
    最近更新 更多