我已经使用 asp.net mvc4 和 razor 开发了一个 Web 应用程序。在我的应用程序中有一个文件上传控件来上传图像并保存在临时位置。
在保存图像之前,应将图像重新调整为特定大小,然后保存在给定的临时位置。
这是我在控制器类中使用的代码。
public class FileUploadController : Controller
{
//
// GET: /FileUpload/
public ActionResult Index()
{
return View();
}
public ActionResult FileUpload()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string relativePath = "~/img/" + Path.GetFileName(uploadFile.FileName);
string physicalPath = Server.MapPath(relativePath);
FileUploadModel.ResizeAndSave(relativePath, uploadFile.FileName, uploadFile.InputStream, uploadFile.ContentLength, true);
return View((object)relativePath);
}
return View();
}
}
这是模型类中使用的代码
public class FileUploadModel
{
[Required]
public HttpPostedFileWrapper ImageUploaded { get; set; }
public static void ResizeAndSave(string savePath, string fileName, Stream imageBuffer, int maxSideSize, bool makeItSquare)
{
int newWidth;
int newHeight;
Image image = Image.FromStream(imageBuffer);
int oldWidth = image.Width;
int oldHeight = image.Height;
Bitmap newImage;
if (makeItSquare)
{
int smallerSide = oldWidth >= oldHeight ? oldHeight : oldWidth;
double coeficient = maxSideSize / (double)smallerSide;
newWidth = Convert.ToInt32(coeficient * oldWidth);
newHeight = Convert.ToInt32(coeficient * oldHeight);
Bitmap tempImage = new Bitmap(image, newWidth, newHeight);
int cropX = (newWidth - maxSideSize) / 2;
int cropY = (newHeight - maxSideSize) / 2;
newImage = new Bitmap(maxSideSize, maxSideSize);
Graphics tempGraphic = Graphics.FromImage(newImage);
tempGraphic.SmoothingMode = SmoothingMode.AntiAlias;
tempGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
tempGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
tempGraphic.DrawImage(tempImage, new Rectangle(0, 0, maxSideSize, maxSideSize), cropX, cropY, maxSideSize, maxSideSize, GraphicsUnit.Pixel);
}
else
{
int maxSide = oldWidth >= oldHeight ? oldWidth : oldHeight;
if (maxSide > maxSideSize)
{
double coeficient = maxSideSize / (double)maxSide;
newWidth = Convert.ToInt32(coeficient * oldWidth);
newHeight = Convert.ToInt32(coeficient * oldHeight);
}
else
{
newWidth = oldWidth;
newHeight = oldHeight;
}
newImage = new Bitmap(image, newWidth, newHeight);
}
newImage.Save(savePath + fileName + ".jpg", ImageFormat.Jpeg);
image.Dispose();
newImage.Dispose();
}
}
但是当我运行应用程序时,它会发生ArgumentException。
它在以下代码行中显示“参数无效”
Bitmap tempImage = new Bitmap(image, newWidth, newHeight);
我如何在这里传递有效和适当的参数
public static void ResizeAndSave(string savePath, string fileName, Stream imageBuffer, int maxSideSize, bool makeItSquare)