此代码返回从字节数组加载的图像的缩略图。我试图理解为什么作者使用4个内存流,如果有一种简单的方法可以重写它,或者它是否正常。

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个MemoryStreams,但他只需要使用2个(我认为)。您应该能够替换此代码:

using (MemoryStream m = new MemoryStream(ms.ToArray()))                
{                    
    return Image.FromStream(m, true);                
}

用这个:

ms.Seek(0, SeekOrigin.Begin);
return Image.FromStream(ms, true);

我认为他创建了第三个MemoryStream,因为 ms MemoryStream不在开头。

其他提示

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;
        }
   }
}

我认为这是对的

我认为以前的答案缺少作者正在强制转换为jpeg。

我认为可以消除最后一个 m 。只需重置 ms.Position = 0 就足够了。请注意,主要的节省是消除 ms.ToArray()

其他MemoryStream看起来是必要的,或者至少通过消除或重新使用它们几乎无法获得。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top