2015-07-11 84 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 
}