我在FileUtility
类中使用此方法来保存图像。
public static void SaveImage(System.IO.Stream file, string savePath, Size size, bool enforceRatio, bool testReverse = false)
{
var image = Image.FromStream(file);
var imageEncoders = ImageCodecInfo.GetImageEncoders();
int enc = Path.GetExtension(savePath).ToLower().Contains("png") ? 4 : 1;
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
Size s = new Size(size.Width, size.Height);
if (testReverse)
{
if (image.Width <= image.Height)
{
if (size.Width <= size.Height)
{
s.Width = size.Width;
s.Height = size.Height;
}
else
{
s.Width = size.Height;
s.Height = size.Width;
}
}
else
{
if (size.Width <= size.Height)
{
s.Width = size.Height;
s.Height = size.Width;
}
else
{
s.Width = size.Width;
s.Height = size.Height;
}
}
}
var canvasWidth = s.Width;
var canvasHeight = s.Height;
var newImageWidth = s.Width;
var newImageHeight = s.Height;
var xPosition = 0;
var yPosition = 0;
if (enforceRatio)
{
var ratioX = s.Width / (double)image.Width;
var ratioY = s.Height / (double)image.Height;
var ratio = ratioX < ratioY ? ratioX : ratioY;
newImageHeight = (int)(image.Height * ratio);
newImageWidth = (int)(image.Width * ratio);
}
var thumbnail = new Bitmap(canvasWidth, canvasHeight);
var graphic = Graphics.FromImage(thumbnail);
if (enforceRatio)
{
graphic.Clear(Color.White);
}
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.DrawImage(image, xPosition, yPosition, newImageWidth, newImageHeight);
thumbnail.Save(savePath, imageEncoders[enc], encoderParameters);
}
效果很好。但是对于一些图像文件(不是每个文件),我得到了
参数异常:参数无效
在第一行var image = Image.FromStream(file);
我称这样的方法:
FileUtility.SaveImage(add2.IconSquare.InputStream, Server.MapPath(program.IconSquare), new System.Drawing.Size { Width = 250, Height = 250 }, false);
add2.IconSquare是一个HttpPostedFileBase
public HttpPostedFileBase IconSquare { get; set; }
唯一的事情是add2来自另一个使用TempData的动作。
var add2 = TempData["Create_Step2"] as AddStep2;
我的意思是我从Action Create_Step2中的用户获取文件并将它们保存在TempData中然后我尝试将它们保存在Action Create_Step3中。谁能告诉我我做错了什么?