Memory problems when Android loads images,
1. Because the stack allocated to images in memory is only 8 Mb, when the image size is too large, memory leakage may occur. How can this problem be solved.
BitmapFactory. Options options = new BitmapFactory. Options ();
Options. inSampleSize = 3; // The image width and height are 1/3 of the original size, that is, the image size is 1/9 of the original size.
// The above code can optimize memory overflow, but it only changes the image size, that is, the thumbnail of the image, and cannot completely resolve the memory overflow
2. Image Compression
Bitmap. compress (Bitmap. CompressFormat. PNG, 80, outStream); // 80 indicates the compression rate, that is, 80%. compress the image and save it.
3. After images are used, the cache should be cleared. Even if the Android virtual machine regularly recycles garbage, java library functions and c library functions are used in the image processing process of Android,
The memory occupied by library functions of c cannot be released through garbage collection. Therefore, we need to manually recycle the memory space of large images after use, otherwise, memory leakage will occur.
Public void clearMemery (Bitmap bitmap ){
If (bitmap! = Null &&! Bitmap. isRecycled ()){
Bitmap. recycle ();
Bitmap = null;
}
}
4. Several ways for Android to read BitMap
A. FileInputStream FCM = new FileInputStream (/sdcard/test.png );
Bitmap bitmap = BitmapFactory. decodeStream (FCM );
B. InputStream inputStream = getBitmapInputStreamFromSDCard ("test.png ");
Bitmap bitmap = BitmapFactory. decodeStream (inputStream );
C. Bitmap bitmap = BitmapFactory. decodeResource (getResources (), R. drawable. test );
D. String SDCarePath = Environment. getExternalStorageDirectory (). toString ();
String filePath = SDCarePath + "/" + "test.png ";
Bitmap bitmap = BitmapFactory. decodeFile (filePath, null );
E. Bitmap bitmap = BitmapFactory. decodeStream (getClass (). getResourceAsStream ("/res/drawable/test.png "));