Search code examples
javaandroidbitmapcrop

Crop Bitmap without reading entire Bitmap first


I have a very large image and I only want to display a section the size of the display (no scaling), and the section should just be the center of the image. Because the image is very large I cannot read the entire image into memory and then crop it. This is what I have so far but it will give OutOfMemory for large images. Also I don't think inSampleSize applies because I want to crop the image, not lower the resolution.

Uri data = getIntent().getData();
InputStream is = getContentResolver().openInputStream(data);
Bitmap bitmap = BitmapFactory.decodeStream(is, null, null);

Any help would be great?


Solution

  • I agree that the easiest way is to break the image up into many smaller tiled images and to just load the appropriate ones to make the image you are after.

    However, if you do not want to do that, you may be forced to look into the encoding of the jpeg itself.

    What you could do is something along the lines of copying the header from the file into a new file, and then extracting just the pixels you want in order to create a new file. Then reloading the new file will allow you to have just the subset of the image you are looking to work with, and all the regular java functionality and classes will be equally available for you to use.

    I know it isn't necessarily an elegant or simple solution, however it does guarantee that you will be able to use the original java functionality which you expect to be able to use.