这一切始于我在Stackoverflow上找到的非常有用的代码片段。
然后,我决定进行自己的调整,并将图像大小调整功能添加到此方法中。 然而,在与这个问题斗争后,我现在得到的信息是:"参数无效"。
我还想强调,尽管出现错误,但图片已经成功上传。 但是,它们没有按预期进行优化。
这是我"上传按钮"中的代码部分:
fuOne.SaveAs(Server.MapPath("~/imgFolder/temp/") + fuOne.FileName);
System.Drawing.Image imgUploaded = System.Drawing.Image.FromFile(Server.MapPath("~/imgFolder/temp/") + fuOne.FileName);
SaveJpeg(Server.MapPath("~/imgFolder/temp/") + fuOne.FileName, imgUploaded, 60, 300, 300);
这是我SaveJpeg方法的完整代码:
public static void SaveJpeg(string path, System.Drawing.Image imgUploaded, int quality, int maxWidth, int maxHeight)
{
if (quality < 0 || quality > 100)
throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");
// resize the image
int newWidth = imgUploaded.Width;
int newHeight = imgUploaded.Height;
double aspectRatio = (double)imgUploaded.Width / (double)imgUploaded.Height;
if (aspectRatio <= 1 && imgUploaded.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)Math.Round(newWidth / aspectRatio);
}
else if (aspectRatio > 1 && imgUploaded.Height > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)Math.Round(newHeight * aspectRatio);
}
Bitmap newImage = new Bitmap(imgUploaded, newWidth, newHeight);
Graphics g = Graphics.FromImage(imgUploaded);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.DrawImage(imgUploaded, 0, 0, newImage.Width, newImage.Height);
g.Dispose();
imgUploaded.Dispose();
// Lets start to change the image quality
EncoderParameter qualityParam =
new EncoderParameter(Encoder.Quality, quality);
// Jpeg image codec
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
System.Drawing.Image imgFinal = (System.Drawing.Image)newImage;
newImage.Dispose();
imgFinal.Save(path, jpegCodec, encoderParams);
imgFinal.Dispose();
}
/// <summary>
/// Returns the image codec with the given mime type
/// </summary>
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
// Get image codecs for all image formats
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
// Find the correct image codec
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
跟进
看起来代码有几个错误。一个是编码问题,另一个是图像保存问题。
Aristos的跟进对解决这个问题非常重要,因为它可以修复我保存文件时犯下的低级错误。