I have bitmap as bmp file (no compressions just a simple bitmap). I want to create memory stream from subsection (a rectangle) of the file without loading the whole file to memory.
Currently, I read the whole bitmap just to be cropped later using a rectangle that represents the points relative to the size of the image.
using (FileStream fs = new FileStream(ImagePath, FileMode.Open))
{
MemoryStream ms = new MemoryStream();
fs.CopyTo(ms);
Image temp = Image.FromStream(ms, false, false);
}
Since bitmap is just a big matrix with color vectors as values can't I create a custom stream to read, only between relevant rows and columns to improve running time and memory usage? The manipulated image never leaves the memory or saved anywhere.
EDIT: Also is there a way to load the file straight to memory stream without using file stream at all?
It sounds like you want to create a custom FileStream that essentially ignores pixel data (by just returning zeros I suppose?) for any region outside of your subrectangle, and thus reduces the total amount of I/O. Yes, it's possible, but it's about as tricky as just writing your own image loader. Your stream would need to understand all the relevant bitmap header information (compression when applicable, bit depth, row order, padding) in order to determine the correct memory offsets for your subrectangle.
I'm not convinced that it will save you much I/O unless the subrectangle is very small compared to the original image. Hard drives will probably going to read data in chunks of about 4k bytes even when you request fewer, so for screen-sized images the biggest performance impact is going to be the total number of rows.
If I were going to go this route (loading only a subrectangle, that is) I would not do it with a custom stream. Instead, I would load the relevant metadata from the bitmap file headers and then create a GDI+ Bitmap object with the correct size and pixel format for the subrectangle. Then you can lock the bitmap and read the pixel data directly into the Bitmap object's memory.
It's not trivial, so don't do it unless you really need to.