2015-07-11 87 views
0

我有文件,這種結構如何閱讀圖像內部(作爲其中的一部分)?

+-------------+-------------+---------------+---------+-------------+ 
| img1_offset | img1_length | Custom Info | Image 1 | Image 2 | 
+-------------+-------------+---------------+---------+-------------+ 

現在我想讀Image 1圖像控制。一種可能的方法是在流中打開此文件(fileStream),將圖像1部分複製到其他流(i1_Stream),然後從i1_Stream讀取圖像。代碼我使用:

using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read)) 
{ 
    using (MemoryStream i1_Stream = new MemoryStream()) 
    { 
     fileStream.Seek(500, SeekOrigin.Begin); // i1_offset 
     fileStream.CopyTo(i1_Stream, 30000); // i1_length 

     var bitmap = new BitmapImage(); 
     bitmap.BeginInit(); 
     bitmap.CacheOption = BitmapCacheOption.OnLoad; 
     bitmap.StreamSource = i1_Stream; 
     bitmap.EndInit(); 
     return bitmap; 
    } 
} 

因爲我需要打開多個文件,這樣在同一時間,我覺得這是更好,如果我可以從fileStream直接讀取Image 1(即負載從50個文件50個圖像WrapPanel。) 。我該怎麼做?謝謝!

+0

http://stackoverflow.com/questions/6949441/how-to-expose-a-sub-section-of-my-stream-to-a-user(不會因爲它不提供複製粘貼解決方案而重複關閉)。 –

回答

0

首先,您應該從輸入流中讀取一個圖像字節數組。 然後將其複製到新位圖:

var imageWidth = 640; // read value from image metadata stream part 
var imageHeight = 480 // same as for width 
var bytes = stream.Read(..) // array length must be width * height 

using (var image = new Bitmap(imageWidth, imageHeight)) 
{ 
    var bitmapData = image.LockBits(new Rectangle(0, 0, imageWidth, imageHeight), 
     System.Drawing.Imaging.ImageLockMode.ReadWrite, // r/w memory access 
     image.PixelFormat); // possibly you should read it from stream 

    // copying 
    System.Runtime.InteropServices.Marshal.Copy(bytes, 0, bitmapData.Scan0, bitmapData.Height * bitmapData.Stride); 
    image.UnlockBits(bitmapData); 

    // do your work with bitmap 
}