简体   繁体   中英

How to simplify this MemoryStream code

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

我认为先前的答案缺少作者强制转换为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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM