Android中的位图内存管理
您好,我正在测试代码以避免加载大量位图时内存崩溃。我有一个关于以下代码的小问题
Bitmap bmp;
long sizepreload, sizepostload,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
);
该片段的返回是:
pre=4260464
post=4333112
bmppixels=26125
ratio=2
所以位图每个像素需要 2 个字节。每像素 16 位对于所有位图都是恒定的,或者是可变的(取决于屏幕密度或图像质量)。如果它是变量,我如何从 Bitmap 类中获取该比率?
提前致谢
这是从网址下载的代码:
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;
}
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, sizepostload,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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
位图每个像素最多可以有 4 个字节,这取决于位图的格式。它不随屏幕密度而变化。但是,在绘制位图时,可能需要根据屏幕密度调整其大小,这会暂时影响您的堆。
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.