Tutorial :Read subsection of Bitmap from disk in C#



Question:

I'm writing some map software for my smartphone and have hit a problem whereby I don't want to load all of the (large) image files into memory when only a portion will be displayed.

Is there a way to read only a subsection (the viewable portion) of a big image given that you know the x and y offsets and width? I know it's probably possibly to do it by reading the file a byte at a time but I'm not sure how to do this.

Thank you, Nico


Solution:1

It's going to depend at least in part on what format(s) your images are saved in. If you have raw image files or bitmaps, it may be possible, but if your data is compressed in any manner, such as JPEG or PNG, it's going to be a lot more difficult to read just a subsection.


Solution:2

If you truly don't want to ever load the full data into memory, you'll have to write your own IO routine that reads the file. For anything more complex than BMP, your decompression algorithm could get complicated.


Solution:3

If it's a BMP file, it shouldn't be that hard.

First you read the header from the file, if I recall correctly it's 44 bytes, but you can find that out from searching the web for a specification.

The header contains information like how many bytes there are per pixel, total width and height, how many bytes per scan line. Normally the bitmap is stored upside down, so you would calculate where in the file the first pixel of the bottom line was and skip to that location. Then you read the pixels you want from that line and skip to the correct pixel on the next line.

The FileStream class has what you need; a Read method for reading and a Seek method to skip to a given position.


Solution:4

Couldn't you cut the image up into sections beforehand?

Splitting it into many 256x256 pixel images means you'd only have to load a couple of them and stitch them back together on the viewable canvas. To name one implementation - google maps uses this technique.


Solution:5

This is something I have done with bitmaps...

public BitmapCropBitmap(BitMap fullBitmap, Rectangle rectangle)  {    return proBitmap.clone(fullBitmap, rectangle, fullBitmap.PixelFormat);  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »