你并不需要先将该文件保存到磁盘,您可以在内存中调整它的大小。我使用类似下面的代码来调整上传到相册的图片大小。 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