views:

317

answers:

3

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);
                }
            }
        }
   }
}
+3  A: 

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.

MusiGenesis
This did it. Thanks
Nick Masao
+1  A: 
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

Trickster
This misses the conversion to jpeg.
Henk Holterman
i think this method should be better names as GetThumbAndConverToJpeg :-) people not always converting to jpeg while getting thumbs
Trickster
Right, but you can never rewrite a method based on it's name alone.
Henk Holterman
+1  A: 

I think the previous answers are missing that the author is forcing a conversion to jpeg.

popester
+1 Good catch. I didn't notice that part. My answer does keep that in, though.
MusiGenesis
-1, should have been a comment under the specific answers.
Henk Holterman