你並不需要先將該文件保存到磁盤,您可以在內存中調整它的大小。我使用類似下面的代碼來調整上傳到相冊的圖片大小。 HttpPostedFile對象有一個InputStream屬性,可以讓你獲得實際的流。 toStream可讓您將輸出流式傳輸到任何您想要的內容(響應,文件等)。它將確保圖片正確縮放以適應640或480寬的盒子。你可能想把它們放在配置文件中而不是硬編碼它們。
private void ResizeImage(Stream fromStream, Stream toStream)
{
const double maxWidth = 640;
const double maxHeight = 480;
using(Image image = Image.FromStream(fromStream))
{
double widthScale = 1;
if(image.Width > maxWidth)
{
widthScale = maxWidth/image.Width;
}
double heightScale = 1;
if(image.Height > maxHeight)
{
heightScale = maxHeight/image.Height;
}
if(widthScale < 1 || heightScale < 1)
{
double scaleFactor = widthScale < heightScale ? widthScale : heightScale;
int newWidth = (int)(image.Width * scaleFactor);
int newHeight = (int)(image.Height * scaleFactor);
using(Bitmap thumbnailBitmap = new Bitmap(newWidth, newHeight))
{
using(Graphics thumbnailGraph = Graphics.FromImage(thumbnailBitmap))
{
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbnailGraph.DrawImage(image, imageRectangle);
ImageCodecInfo jpegCodec = ImageCodecInfo.GetImageEncoders()
.FirstOrDefault(c => c.FormatDescription == "JPEG");
if(jpegCodec != null)
{
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
thumbnailBitmap.Save(toStream, jpegCodec, encoderParameters);
}
else
{
thumbnailBitmap.Save(toStream, ImageFormat.Jpeg);
}
}
}
}
else
{
image.Save(toStream, ImageFormat.Jpeg);
}
}
}
+1。我刪除了我的答案,你的更好。 – 2012-01-06 19:06:56