2009-10-22 77 views
2

此代碼返回從字節數組加載的圖像的縮略圖。我試圖理解爲什麼作者正在使用4個內存流,以及是否有一種簡單的重寫方式,或者它是否正確。如何簡化此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())) 
     { 
      // 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

他實際上只在這裏使用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的不是開頭。

+0

這樣做了。謝謝 – 2009-10-23 09:57:14

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

我認爲這將是正確的

+1

這錯過了轉換爲jpeg。 – 2009-10-22 16:05:42

+1

我認爲這個方法應該是更好的名字GetThumbAndConverToJpeg :-)人們並不總是轉換爲JPEG,而得到大拇指 – 2009-10-22 16:30:35

+0

正確,但你永遠不能重寫基於它的名字的方法。 – 2009-10-23 10:21:39

1

我覺得以前的答案是缺少筆者強制轉換爲JPEG。

+0

+1好抓。我沒有注意到這一部分。不過,我的回答確實保留了這一點。 – MusiGenesis 2009-10-22 16:05:20

+0

-1,應該是根據具體答案做出評論。 – 2009-10-22 16:10:11

1

我認爲最後一個,m,可以被淘汰。簡單重置ms.Position=0就足夠了。請注意,主要節省將消除ms.ToArray()

其他MemoryStreams看起來是必要的,或者至少通過消除或重複使用它們幾乎沒有什麼收穫。