Prevent memory overflow when loading large local files as background images

Try not to use setImageBitmap or setImageResource or BitmapFactory.decodeResource to set a large image, because these functions are finally completed through createBitmap in the java layer after decoding, which consumes more memory. 

Therefore, use the BitmapFactory.decodeStream method to create a bitmap first, and then set it as the source of the ImageView. The biggest secret of decodeStream is that it directly calls JNI>>nativeDecodeAsset() to complete the decode, no need to use the createBitmap of the java layer , thus saving the space of the java layer.
If you add the Config parameter of the picture when reading, you can effectively reduce the memory loaded, thereby effectively preventing the throwing of out of Memory exception
In addition, decodeStream directly takes the picture to read the bytecode, and will not automatically adapt to the various resolutions of the machine. After using decodeStream, you need to configure the corresponding picture resources in hdpi, mdpi, and ldpi. The resolution machines are all the same size (the number of pixels), and the displayed size is wrong. 

	/**
	* 以最省内存的方式读取本地资源的图片
	* @param context
	* @param resId
	* @return
	*/
	public static Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		//获取资源图片  
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}


https://tinypng.com image processing URL

Reference: http://263229365.iteye.com/blog/1562924

Guess you like

Origin blog.csdn.net/daweibalang717/article/details/73800088