How to simplify this MemoryStream code
This code returns a thumbnail of the image loaded from a byte array. I am trying to understand why the author is using 4 memory streams and if there is an easy way to rewrite this or if everything is ok like this.
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);
}
}
}
}
}
+2
source to share
4 answers
It actually only uses 3 MemoryStreams, but it only needs to use 2 (I think). You must 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 it created a third MemoryStream because the ms
MemoryStream was not in the beginning.
+3
source to share
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 it will be right
+1
source to share