This code returns a thumbnail of an image loaded from a byte array. I'm trying to understand why the author is using 开发者_开发问答4 memory streams and if there is a simple way of rewriting this or if it is okay the way it is.
public Image GetThumbnail(int height, int width)
{
//load the image from a byte array (imageData)
using (MemoryStream mem = new MemoryStream(this.imageData))
{
// Create a Thumbnail from the image
using (Image thumbPhoto = Image.FromStream(mem,
true).GetThumbnailImage(height, width, null,
new System.IntPtr()))
{
// Convert the Image object to a byte array
using (MemoryStream ms = new MemoryStream())
{
thumbPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
using (MemoryStream m = new MemoryStream(ms.ToArray()))
{
return Image.FromStream(m, true);
}
}
}
}
}
He's actually only using 3 MemoryStreams here, but he needs to only use 2 (I think). You should be able to replace this code:
using (MemoryStream m = new MemoryStream(ms.ToArray()))
{
return Image.FromStream(m, true);
}
with this:
ms.Seek(0, SeekOrigin.Begin);
return Image.FromStream(ms, true);
I think he created the third MemoryStream because the ms MemoryStream wasn't at the beginning.
public Image GetThumbnail(int height, int width)
{
//load the image from a byte array (imageData)
using (MemoryStream mem = new MemoryStream(this.imageData))
{
// Create a Thumbnail from the image
using (Image thumbPhoto = Image.FromStream(mem,
true).GetThumbnailImage(height, width, null,
new System.IntPtr()))
{
return thumbPhoto;
}
}
}
i think this will be right
I think the previous answers are missing that the author is forcing a conversion to jpeg.
I would think the last one, m, can be eliminated. Simply resetting ms.Position=0 would be enough. Note that the main savings would to eliminate the ms.ToArray().
The other MemoryStreams look necessary, or at least there is little to be gained by eliminating or re-using them.
加载中,请稍侯......
精彩评论