I have a problem when creating a bitmap from a MapView (osmdroid). This map takes almost the entire screen of a phone (always in portrait mode). I want to create a bitmap from a square of the center of the displayed map (side size : the screen width) and save it in a file to use it after in my app.
A picture says more than a thousand words so I drew this :
This is the method I use to get the bitmap :
public static Bitmap loadBitmapFromMapView(final MapView mapview, final int width, final int height) {
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
mapview.setDrawingCacheEnabled(true);
b = Bitmap.createBitmap(mapview.getDrawingCache(), 0, ((height - width) / 2), width, width);
mapview.setDrawingCacheEnabled(false);
return b;
}
And then :
public static File saveBitmapAsFile(final Bitmap bmp) {
if (mSaveDirectory == null || !mSaveDirectory.exists()) {
final ContextWrapper cWrapper = new ContextWrapper(getApplicationContext());
mSaveDirectory = cWrapper.getFilesDir();
if (!mSaveDirectory.exists()) {
mSaveDirectory.mkdirs();
}
}
try {
final String imageName = "Image_" + System.currentTimeMillis() + ".png";
final File file = new File(mSaveDirectory, imageName);
final FileOutputStream out = getApplicationContext().openFileOutput(imageName, Context.MODE_WORLD_READABLE);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
return file;
} catch (final Exception e) {
e.printStackTrace();
}
return null;
}
The problem is in my first method, two times out of three, I have a OutOfMemoryException at this line :
b = Bitmap.createBitmap(mapview.getDrawingCache(), 0, ((height - width) / 2), width, width);
When the exception isn't thrown, it works well and my map is saved in the good format.
I searched a lot but I didn't find a solution that work and resolve the OutOfMemory error on a createBitmap from a view.
If you know a way to solve it, it would be great, ask me if you need more informations and sorry for my English.
Thanks !
Aenur56