Bitmap memory management in Android
Hello im testing code for avoid memory crashes when loading a lot of bitmaps. And I have a little question, about the following code
Bitmap bmp;
long sizepreload, sizepos开发者_Go百科tload,bmppixels;
sizepreload= Debug.getNativeHeapAllocatedSize();
bmp=getImageBitmapFromUrl("http://www.google.com/intl/en_com/images/srpr/logo2w.png");
sizepostload=Debug.getNativeHeapAllocatedSize();
bmppixels=bmp.getHeight()*bmp.getWidth();
Log.d("bmp test","pre="+sizepreload+"\n" +
"post="+sizepostload+"\n" +
"bmppixels="+bmppixels+"\n"+
"ratio="+(sizepostload-sizepreload)/bmppixels
);
The return of that snippet is:
pre=4260464
post=4333112
bmppixels=26125
ratio=2
So a bitmap takes 2 bytes per pixel. 16 bits per pixel is constant for all bitmaps or it is variable (depending of screen density or image quality). If its variable how can I get that ratio from the Bitmap class?
thanks in advance
Thats the code for download from a url:
public static Bitmap getImageBitmapFromUrl(String url){
URL aURL;
Bitmap result = null;
try {
aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
result= BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
result=null;
e.printStackTrace();
}
return result;
}
Bitmaps can be up to 4 bytes per pixel, this depends on the bitmap's format. It is not variable for the screen density. However when drawing the bitmap, it may need to be resized for the screen density, and this would affect your heap temporarily.
精彩评论