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


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


I think the previous answers are missing what the author is forcing to convert to jpeg.

+1


source


I think that the last m

one can be eliminated. A simple reset ms.Position=0

would be sufficient. Please note that major savings will result in elimination ms.ToArray()

.

Other MemoryStreams seem necessary, or at least little can be achieved by eliminating or reusing them.

+1


source







All Articles