【发布时间】:2015-05-29 04:25:37
【问题描述】:
当我有以下条件时,我想将图像裁剪为 5/3.5 的比例:
- 图像的虚拟路径(~/Uploads/Images)
- 图像左上角的 X 点
- 图像左上角的 Y 点
- 图像宽度
- 图像高度
这是一张显示我的意思的图片:
突出显示的部分是我所拥有的。
如何在我的 MVC 控制器中使用 C# 实现这一点?我还想将图像存储回其原始位置,尽可能覆盖旧图像。
【问题讨论】:
标签: c# asp.net-mvc-5 crop jcrop
当我有以下条件时,我想将图像裁剪为 5/3.5 的比例:
这是一张显示我的意思的图片:
突出显示的部分是我所拥有的。
如何在我的 MVC 控制器中使用 C# 实现这一点?我还想将图像存储回其原始位置,尽可能覆盖旧图像。
【问题讨论】:
标签: c# asp.net-mvc-5 crop jcrop
您仍然可以在 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();
}
【讨论】:
System.Drawing?
Image.FromFile(imgPath); 我收到一个错误,说它无法加载文件! imgPath 是 ~/uploads/images。我需要对路径做一些特别的事情吗?
c:/uploads/images/someImage.jpg 不确定~/uploads/images/someImage.jpg 是否有效,但您可以尝试
.FromFile() 需要完整路径,否则它会在同一个目录中查找。知道如何从~/uploads/images 到x:/work/app/uploads/images/ 吗?