当前位置:网站首页>How much memory does bitmap occupy in the development of IM instant messaging?
How much memory does bitmap occupy in the development of IM instant messaging?
2022-07-25 20:06:00 【wecloud1314】
This article deals with the discussion of screen density , We need to find out first DisplayMetrics Two variables of , Simply speaking , It can be understood as density The value is 1dp=density px;densityDpi Is the number of points per inch of the screen ( Not pixels ), stay DisplayMetrics among , The relationship between these two is linear : In order not to cause confusion , Unless otherwise specified , All means densityDpi, Of course, if you like , It can also be used. density To illustrate the problem . in addition , The basis of this paper mainly comes from android 5.0 Source code , Other versions may be slightly different .

The system has provided Bitmap Memory usage calculation method
Friends who do mobile client development must have had a headache because of figure , Speaking of, there have been leader Because a guy in the group added a picture to the project jpg I want to lose my temper , ha-ha . Why do you have a headache ? Eat memory , I'll give it back to you from time to time OOM Chong Chong Xi , Make your day interesting ( It's hopeless ). Every time a picture is added to the project , We all need to be concerned about how big a hole this product will take , How big is it ?
Android API There is a convenient calculation method :
public final int getByteCount() {
// int result permits bitmaps up to 46,340 x 46,340
return getRowBytes() * getHeight();
}
Through this method , We can get a Bitmap How much memory does it take at runtime .
for instance :
a sheet 522x686 Of PNG picture , I put it in drawable-xxhdpi Under the table of contents , At Samsung s6 Load on , Take up memory 2547360B, You can use this method to get .
Bitmap What strategy is used to calculate the memory occupation ?
Ask every time Bitmap How old are you .. It's weird , After all, we can't always ask , Instead of figuring out why it is so big . Can you give it a life , Calculate how big it is ? Of course you can , It's very simple , We directly follow the vine , Find out the real culprit , Oh no , Find out the answer .
1getByteCount
getByteCount We have just known the source code of , When we ask Bitmap When it comes to size , This child also gets the date of birth first , And then calculate , So here comes the question ,getHeight Is the height of the picture ( Company :px),getRowBytes What is it? ?
public final int getrowBytes() {
if (mRecycled) {
Log.w(TAG, "Called getRowBytes() on a recycle()'d bitmap! This is undefined behavior!");
}
return nativeRowBytes(mFinalizer.mNativeBitmap);
}
forehead , It feels so right , want JNI 了 . Because I C++ It's really used less , Every time I think of JNI Please imagine the scene of your forehead hitting the wall , But what? , Grandfather Mao said , All reactionaries are paper tigers ~ And nativeRowBytes The corresponding function is as follows .
Bitmap.cpp:
static jint Bitmap_rowBytes(JNIEnv* env, jobject, jlong bitmapHandle) {
SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle)
return static_cast<jint>(bitmap->rowBytes());
}
wait , We seem to have found something , original Bitmap It's essentially one SkBitmap.. And this SkBitmap It's also a big source , I don't believe you :Skia. Don't say anything , Take a quick look SkBitmap.
SkBitmap.h:
/** Return the number of bytes between subsequent rows of the bitmap. */
size_t rowBytes() const { return fRowBytes; }
good , Tracked here , We found that ARGB_8888( That's what we use most Bitmap The format of ) One pixel of 4byte, that rowBytes It's actually 4*width bytes.
Then the conclusion comes out , a sheet ARGB_8888 Of Bitmap The calculation formula of memory consumption :bitmapInRam = bitmapWidth*bitmapHeight *4 bytes. Speaking of which, do you think the story is over ? Try it if you have the ability , There will always be a multiple between what you calculate and what you get , Why? ? Remember the example we gave at the beginning ?
a sheet 522*686 Of PNG picture , I put it in drawable-xxhdpi Under the table of contents , At Samsung s6 Load on , Take up memory 2547360B, You can use this method to get . Instant messaging chat software app Development of the v:weikeyun24 consulting

However, the formula calculates 1432368B...
Density
You know why I tried so hard to say "put..." when giving examples xxx Under the table of contents , Let's say it's useful xxx Mobile phone ? Do you think Bitmap Loading is only related to width and height ?Naive. Or look at the code first , What we read is drawable Pictures below the directory , It's using decodeResource Method , This method is essentially two steps :
- Read the original resource , This calls Resource.openRawResource Method , After this method call is completed, it will call TypedValue Assign a value , It contains the original resources density Etc ;
- call decodeResourceStream Decode and adapt the original resources . This process is actually the original resources density To screen density A mapping of .
Of original resources density In fact, it depends on the directory where the resources are stored ( such as xxhdpi The corresponding is 480), And the screen density Assignment , Look at this code .
So we can easily see ,Option.inScreenDensity This value is not initialized , In fact, we will see later that this value will not be used at all ; What should we care about most ? yes inDensity and inTargetDensity, These two values are the same as the following cpp In the document density and targetDensity Corresponding —— Repeat ,inDensity Is the original resources density,inTargetDensity It's the screen density.
Then , Yes nativeDecodeStream Method , Unimportant code is skipped directly , Directly give the most critical doDecode Function code .
Notice one of them density and targetDensity, The former is decodingBitmap Of density, This value is related to the directory where the image is placed ( such as hdpi yes 240,xxhdpi yes 480), I followed this part of the code , Is too long. , Don't list .
targetDensity In fact, it is our goal to load pictures density, The source of this value has been given above , Namely DisplayMetrics Of densityDpi, If it's Samsung s6 So this number is 640.sx and sy In fact, it is approximately equal to scale Of , because scaledWidth and scaledHeight By width and height multiply scale Got . We see Canvas Magnified scale times , And then read the one in the memory bitmap Draw up , It's equivalent to taking this bitmap Magnified scale times .
Let's look at our example :
a sheet 522*686 Of PNG picture , I put it in drawable-xxhdpi Under the table of contents , At Samsung s6 Load on , Take up memory 2547360B, among density Corresponding xxhdpi by 480,targetDensity Corresponding to Samsung s6 The density of is 640: 522/480 * 640 * 686/480 *640 * 4 = 2546432B
precision
It's getting more and more interesting, isn't it , You will surely find that our detailed calculation is still different from the obtained value ! Why? ? Because the result is very close , We naturally think of the problem of accuracy . Come on , Take out another sentence in the above code :
outputBitmap->setInfo(SkImageInfo::Make(scaledWidth, scaledHeight,
colorType, decodingBitmap.alphaType()));
We see the final output outputBitmap Its size is scaledWidth*scaledHeight, Let's show you the fragments of the calculation of these two variables :
if (willScale && decodeMode != SkImageDecoder::kDecodeBounds_Mode) {
scaledWidth = int(scaledWidth * scale + 0.5f);
scaledHeight = int(scaledHeight * scale + 0.5f);
}
In our case :
scaledWidth = int( 522 * 640 / 480f + 0.5) = int(696.5) = 696
scaledHeight = int( 686 * 640 / 480f + 0.5) = int(915.16666…) = 915
Here's the moment to witness the miracle :
915 * 696 * 4 = 2547360
Youmu is very excited ! Youmu is very excited !! Write here , All of a sudden 《STL Source analysis 》 The title page of a book , Mr. Hou Jie only wrote one sentence :“ Before source code , No secret ”.
边栏推荐
- Difference Between Accuracy and Precision
- 高数_第3章重积分 学习体会与总结
- Univariate function integration_ Partial integral method
- Day7: ordered binary tree (binary search tree)
- 「分享」DevExpress ASP.NET v22.1最新版本系统环境配置要求
- Share 25 useful JS single line codes
- 软件设计师下午真题:2009-2022
- Log in to Baidu online disk with cookies (websites use cookies)
- 4. Server startup of source code analysis of Nacos configuration center
- PyTorch 模型 onnx 文件的导出和调用
猜你喜欢

Socket error Event: 32 Error: 10053. Connection closing...Socket close

C language learning diary 3 - realloc function

C # add multi line and multi column text watermark in word

【高等数学】【8】微分方程

Google pixel 6A off screen fingerprint scanner has major security vulnerabilities

The query data returned by the print database is null or the default value. Does not match the value returned by the database

wallys//wifi6 wifi5 router IPQ6018 IPQ4019 IPQ4029 802.11ax 802.11ac

Distributed link logging minbox logging usage document

919. Complete binary tree inserter

Concept of IP address
随机推荐
Distributed link logging minbox logging usage document
Array of sword finger offer question bank summary (I) (C language version)
Prescan quick start to master Lesson 19: prescan actuator configuration, track synchronization and non configuration of multiple tracks
Recommendations on how to install plug-ins and baby plug-ins in idea
[wp]ctfshow-web introductory information collection
FormatDateTime说解[通俗易懂]
分享 25 个有用的 JS 单行代码
【高等数学】【6】多元函数微分学
笔记——记录一个CannotFindDataSourceException: dynamic-datasource can not find primary datasource问题解决
Skiing mobile H5 game source code download
The use of new promise, async and await in the project, and the practical application of promise.all in the project
qml 结合 QSqlTableModel 动态加载数据 MVC「建议收藏」
Notes - record a cannotfinddatasourceexception: dynamic datasource can not find primary datasource problem solving
PMP每日一练 | 考试不迷路-7.25
How to ensure the quality of customized slip rings
Deeplobv1 and V2
C语言学习日记3——realloc函数
接口请求合并的3种技巧,性能直接爆表!
Ml programming skills:
Configure and install cocos2dx development environment under Tongxin UOS