我有这种结构的文件
+-------------+-------------+---------------+---------+-------------+
| img1_offset | img1_length | Custom Info | Image 1 | Image 2 |
+-------------+-------------+---------------+---------+-------------+
现在我想阅读Image 1
来进行图像控制。一种可能的方法是在流(fileStream
)中打开此文件,将图像1部分复制到其他流(i1_Stream
),然后从i1_Stream
读取图像。代码I使用:
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;
}
}
因为我需要一次打开许多这样的文件(即将50个图像从50个文件加载到WrapPanel),我认为如果我可以直接从Image 1
阅读fileStream
,那就更好了。我怎么能这样做?谢谢!
答案 0 :(得分: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
}