0

I have files with this structure

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

Now I want to read Image 1 to image control. One possible way is open this file in a stream (fileStream), copy image 1 part to other stream (i1_Stream) then read image from i1_Stream. Code I'm using:

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

Because I need open many file like this at one time (ie. load 50 images from 50 files to WrapPanel), I think it is better if I can read Image 1 directly from fileStream. How I can do that? Thank!

Alex H
  • 1,424
  • 1
  • 11
  • 25
NoName
  • 7,940
  • 13
  • 56
  • 108
  • http://stackoverflow.com/questions/6949441/how-to-expose-a-sub-section-of-my-stream-to-a-user (not closing as duplicate as it does not provide copy-paste solution). – Alexei Levenkov Jul 11 '15 at 02:53

1 Answers1

0

First, you should read an array of image bytes from input stream. Then copy it into new bitmap:

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
}
ahydrax
  • 73
  • 1
  • 6