我的目標是調整圖像的大小,如果超過一定的高度或寬度,保持相同的長寬比。這是我到目前爲止:我的方法在保持相同寬高比的同時調整圖像大小有什麼問題?
static public Stream ScaleImage(HttpPostedFileBase imageFile)
{
Stream stream = new MemoryStream();
var maxWidth = 500;
var maxHeight = 500;
var image = Image.FromStream(imageFile.InputStream, true, true);
if (image.Width > maxWidth || image.Height > maxHeight)
{
// something in here is broken
var ratioX = (double)maxWidth/image.Width;
var ratioY = (double)maxHeight/image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(image, newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
Bitmap bmp = new Bitmap(newImage);
bmp.Save(stream, ImageFormat.Jpeg);
stream.Close();
}
else
{
// this works fine
image.Save(stream, ImageFormat.Jpeg);
stream.Close();
}
return stream;
}
如果圖像是在最大尺寸下,那麼它工作正常。但是,如果它需要調整大小,然後由於某種原因,我不能當場,返回流是充滿了錯誤:
爲什麼你要返回封閉流? – john
我需要發送圖像並且無法控制的API需要一個流。但這不是重點,因爲在不重新調整大小時,保存到Stream中工作得很好。 –
如果你這麼說。我剛剛遇到與不需要調整大小的圖像相同的錯誤。在調用'stream.Close()'之前,沒有任何ObjectDisposedException錯誤,但在調用它之後,它們就在那裏。我確實需要調用'stream.Seek(0,SeekOrigin.Begin);'以使流可用,但它可以工作。 – john