当前位置:网站首页>Solutions to oom caused by pictures in res directory
Solutions to oom caused by pictures in res directory
2022-07-24 19:23:00 【Martin-Rayman】
Reference link :http://blog.csdn.net/coderinchina/article/details/40964205
Reference link :http://blog.csdn.net/shineflowers/article/details/41648745
More pictures are needed in recent projects , And the picture takes up a lot of pixels and memory . Cause oneortwo pictures to come down directly OOM 了 .
For this difficult problem , I have referred to many blog posts these two days .
So let's first understand what happens because the picture is too large OOM
The memory allocated by the current machine for each process is about 32M, But when the phone memory is not enough to allocate 32M When ~ Or when this app The running memory of is greater than 32M Will cause OOM.
So let's focus on the picture first .
Android How to calculate the memory size of a picture in : The picture is long * wide * Number of pixel bytes occupied , And the number of pixel bytes Android There are only four kinds ,
1:ALPHA_8 Occupy 1 Bytes
2:ARGB_4444 Occupy 2 Bytes
3:ARGB_8888 Occupy 4 Bytes
4:RGB_565 Occupy 2 Bytes
transparency Red green Blue
And these bytes can be passed bitmap Object to set bitmap.setConfig(Bitmap.Config.ARGB_4444);
If this is a fixed value , Then change the size of a picture , You can only change the width or height , If only higher , If width does not change , It will deform the picture , Therefore, it is generally changed together , So the picture should be scaled , When zooming, it scales according to the width and height of the screen , because Android There's a lot of equipment , The width and height of each screen are also different , In this way, you can load large pictures to avoid OOM.
For example, a picture used in a recent project 1280*720 Pixel image , And it uses ARGB_8888, Then calculate the memory occupied :1280*720*4/1024/1024=3.5M A picture
So a few pictures like this can put Android Memory burst .
Looking at the above formula, you also know that loading pictures into memory is to see The image Pixels and quality determine its size in the running memory
Then it summarizes the best solution :
Compress compress or compress pictures ( But there are two compression methods )
The first way : Compress the scale of the picture ( Code reference to major websites )
We can set BitmapFactory.Optiions Of inJustDecodeBounds The attribute is true, In this case, the image will not be loaded into memory ,
But the picture will be width and height Properties are read , We can use this attribute to bitmap Compress .Options.inSampleSize The compression ratio can be set .
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
// The height and width of the source picture
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 scale
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,int reqWidth, int reqHeight) {
// The first analysis will inJustDecodeBounds Set to true, 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 inSampleSize value
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Use obtained inSampleSize Value parses the image again
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
} The second way : The quality of the compressed image
We know from the formula just mentioned , We can go through bitmap.setConfig(Bitmap.Config.ARGB_4444) To set specific Bitmap The display quality of . The following method refers to this method
<pre name="code" class="java" style="color: rgb(51, 51, 51); font-size: 12.5px; letter-spacing: 0.5px; line-height: 22.5px;"> public Bitmap readBitMap(Context context, int resId) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
// Get resource pictures
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is, null, opt);
} among resId It can be passed in directly Drawable Files in the file directory ( Don't put pictures with raw Under the table of contents )The following is what I met these days OOM Solutions for , The effect of the second method is quite good .
边栏推荐
- On July 31, 2022, the dama-cdga/cdgp data governance certification class was opened!
- Chapter 4 compound type
- OPENGL学习(五)Modern OpenGL 三角形绘制
- 文献阅读:GoPose 3D Human Pose Estimation Using WiFi
- 思源笔记 v2.1.2 同步问题
- 第4章 复合类型
- Why are there loopholes in the website to be repaired
- Tclsh array operation
- [understanding of opportunity-48]: Guiguzi - Chapter 7 - collect information in advance, make predictions and implementation plans in advance
- Those gods on Zhihu reply
猜你喜欢

PostgreSQL Elementary / intermediate / advanced certification examination (7.16) passed the candidates' publicity

FPGA 20个例程篇:9.DDR3内存颗粒初始化写入并通过RS232读取(上)

Clion configuring WSL tool chain

Tencent Browser service TBS usage

PostgreSQL weekly news - July 13, 2022

Pay close attention! List of the latest agenda of 2022 open atom open source Summit

拿捏C指针

Literature reading: gopose 3D human pose estimation using WiFi

How does PostgreSQL decide PG's backup strategy

文献阅读:GoPose 3D Human Pose Estimation Using WiFi
随机推荐
[JVM learning 04] JMM memory model
Summer Niuke multi school 1:i chiitoitsu (expectation DP, inverse yuan)
Arrays
Literature reading: gopose 3D human pose estimation using WiFi
Anaconda installs labelimg (super simple and available)
【校招面经】8道指针面试真题,快来检测自己掌握了几道。
Install SSL Certificate in Litespeed web server
MySQL index principle and query optimization "suggestions collection"
Tcl/tk grouping and replacement rules
Day 4 (item 1: household income and expenditure records)
Tclsh array operation
Hold the C pointer
In the spring of domestic databases
OPENGL学习(四)GLUT三维图像绘制
Techempower web framework performance test 21st round results release --asp Net core continue to move forward
Common methods of string class
Get module handle / base address
2022 Summer Games of Hangzhou electric power multiple schools 1012aalice and Bob (game theory)
MySQL1
Colon sorting code implementation