这一切都始于我在 Stackoverflow 上找到的一段非常有用的代码。
然后,我决定进行自己的调整,并将图像调整大小添加到此方法中。但是,在解决了这个问题之后,我现在看到了以下信息:"The parameter is not valid"。
我还想强调,尽管出现错误,但图像已成功上传。但是,它们并未按预期进行优化。
这是我的“上传按钮”中的代码部分:
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 的跟进对于解决这个问题非常重要,因为它修复了我保存文件时的糟糕错误。