Android efficiently loads large images to avoid OOM
Images are often loaded in our projects. Sometimes, if there are too many images to be loaded, the program will become very slow. If the OOM is heavy, the App will be suspended. Translate https://developer.android.com/training/displaying-bitmaps/index.html to learn the functions.
Images have various shapes and sizes, but in most cases, these images will be larger than the size required by our program. For example, most of the images displayed in the System Image Library are taken by mobile phone cameras. The resolution of these images is much higher than that of our mobile phone screen. We should know that all the applications we write have certain memory limitations. If the program occupies too much memory, it is prone to OOM (OutOfMemory) exceptions. The following code shows the maximum memory available for each application.
[Java]View plaincopyprint?
- Int maxMemory = (int) (fig. getRuntime (). maxMemory ()/1024/1024 );
Currently, most mobile phones are 32 MB. Since we know the memory allocated by each app, We need to calculate how many images are loaded without causing OOM, therefore, we need to calculate the memory occupied by each image.
Calculation of the memory size of an image in Android: The image length * width * occupies the number of pixel bytes, and the number of pixel bytes is four in Android,
1: ALPHA_8 occupies 1 byte
2: ARGB_4444 occupies 2 bytes
3: ARGB_8888 occupies 4 bytes
4: RGB_565 occupies 2 bytes
Note: ARGB refers to A color pattern in which A represents Alpha, R represents red, G Represents green, and B Represents blue. In fact, all visible colors are composed of red, green, and blue, therefore, red, green, and blue are also called primary colors. A R G B
Transparency red green blue
These bytes can be set through the bitmap object, bitmap. setConfig (Bitmap. config. ARGB_4444); if this is a value, you can only change the width or height of an image to change the size of an image. If it is only increased and the width remains unchanged, the image deformation will occur, therefore, the image is usually scaled together, and scaled Based on the width and height of the screen. Because there are many Android devices, the width and height of each screen are different, in this way, you can load large images to avoid OOM.
[Java]View plaincopyprint?
- The BitmapFactory class provides multiple parsing methods (decodeByteArray, decodeFile, decodeResource, etc.) for creating Bitmap objects. We should select an appropriate method based on the image source. For example, the decodeFile method can be used for images on the SD card, the decodeStream method can be used for images on the network, and the decodeResource method can be used for images in resource files. These methods will try to allocate memory for the constructed bitmap, which will easily lead to OOM. Therefore, each parsing method provides an optional BitmapFactory. the Options parameter. If the inJustDecodeBounds attribute of this parameter is set to true, the resolution method cannot allocate memory to bitmap. The returned value is no longer a Bitmap object, but null. Although Bitmap is null, The outWidth, outHeight, and outMimeType attributes of BitmapFactory. Options are assigned values. This technique allows us to obtain the length and width of the image and the MIME type before loading the image, so as to compress the image as needed. The following code is used:[Java]View plaincopyprint?
- BitmapFactory. Options options = new BitmapFactory. Options ();
- Options. inJustDecodeBounds = true;
- BitmapFactory. decodeResource (getResources (), R. id. myimage, options );
- Int imageHeight = options. outHeight;
- Int imageWidth = options. outWidth;
- String imageType = options. outMimeType; for example, a 480*800 image is directly loaded into the memory. If there are many images, it will easily cause OOM, and compression is required, for example, compression by 1/8, after compression, the image size is 60*100. If the image size obtained from the server is different, the image size after compression must be different on the ImageView, because the ImageView width and height must be set to wrap_content.
Now, write a Demo to zoom in the image:
[Java]View plaincopyprint?
- Package com. jackie. bitmapdemo;
-
- Import android. app. Activity;
- Import android. content. res. Resources;
- Import android. graphics. Bitmap;
- Import android. graphics. BitmapFactory;
- Import android. OS. Bundle;
- Import android. widget. ImageView;
-
- Public class MainActivity extends Activity {
- Private ImageView imageView;
- @ Override
- Protected void onCreate (Bundle savedInstanceState ){
- Super. onCreate (savedInstanceState );
- SetContentView (R. layout. activity_main );
- ImageView = (ImageView) findViewById (R. id. iv );
- Bitmap bitmap = decodeSampledBitmapFromResource (getResources (), R. drawable. B, 60,100 );
- Iv. setImageBitmap (bitmap );
- }
-
- Public static int calculateInSampleSize (BitmapFactory. Options options,
- Int reqWidth, int reqHeight ){
- // Height and width of the source Image
- Final int height = options. outHeight;
- Final int width = options. outWidth;
- Int inSampleSize = 1;
- If (height> reqHeight | width> reqWidth ){
- // Calculate the ratio of actual width to target width.
- Final int heightRatio = Math. round (float) height/(float) reqHeight );
- Final int widthRatio = Math. round (float) width/(float) reqWidth );
- // Calculate the scaling ratio
- InSampleSize = heightRatio <widthRatio? HeightRatio: widthRatio;
- }
- Return inSampleSize;
- }
- Public static Bitmap decodeSampledBitmapFromResource (Resources res, int resId,
- Int reqWidth, int reqHeight ){
- // Set inJustDecodeBounds to true for the first resolution to get the image size.
- Final BitmapFactory. Options options = new BitmapFactory. Options ();
- Options. inJustDecodeBounds = true;
- BitmapFactory. decodeResource (res, resId, options );
- // Call the method defined above to calculate the inSampleSize Value
- Options. inSampleSize = calculateInSampleSize (options, reqWidth, reqHeight );
- // Use the obtained inSampleSize value to parse the image again
- Options. inJustDecodeBounds = false;
- Return BitmapFactory. decodeResource (res, resId, options );
- }
-
- } There are two ways to calculate the scaling ratio:
1: scale the Image Based on the screen width and height
2: scale according to the width and height after the scaling. The above example is based on this.