当前位置:网站首页>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 ”.
边栏推荐
- 什么是聚类分析?聚类分析方法的类别[通俗易懂]
- High number_ Chapter 3 learning experience and summary of multiple integral
- Creative drop-down multi choice JS plug-in download
- wallys//wifi6 wifi5 router IPQ6018 IPQ4019 IPQ4029 802.11ax 802.11ac
- Three skills of interface request merging, and the performance is directly exploded!
- How to ensure the quality of customized slip rings
- Binarysearch basic binary search
- JVM(二十三) -- JVM运行时参数
- Deeplobv1 and V2
- 【高等数学】【8】微分方程
猜你喜欢

Six axis sensor use learning record

Legal mix of collations for operation 'Union' (bug record)

随机梯度下降法、牛顿法、冲量法、AdaGrad、RMSprop以及Adam优化过程和理解
![Interpretation of repartitioned network structure in repvgg network [with code]](/img/0b/a2f3b312899043c9d5b9c7d6b22261.png)
Interpretation of repartitioned network structure in repvgg network [with code]

sentinel简单限流和降级demo问题记录

Difference Between Accuracy and Precision

Recommendations on how to install plug-ins and baby plug-ins in idea

Rainbond插件扩展:基于Mysql-Exporter监控Mysql

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

【高等数学】【4】不定积分
随机推荐
什么是聚类分析?聚类分析方法的类别[通俗易懂]
Distributed link logging minbox logging usage document
Yyds dry inventory how to locate browser page crash
各厂商网络虚拟化的优势
Application of conductive slip ring in mechanical equipment
RF、GBDT、XGboost特征选择方法「建议收藏」
RF, gbdt, xgboost feature selection methods "recommended collection"
tiktok手机网络环境怎么设置?tiktok怎么破播放量?
When the V100 of mindpole 8 card is trained to 101 epochs, an error of reading data timeout is reported
Can you tell me whether mindspore supports torchvision Model directly uses the pre trained network, such as vgg16
VMware 虚拟机下载、安装和使用教程
随机梯度下降法、牛顿法、冲量法、AdaGrad、RMSprop以及Adam优化过程和理解
Siemens-PLM-TeamCenter下载、安装、使用教程
PreScan快速入门到精通第十八讲之PreScan轨迹编辑的特殊功能
qml 结合 QSqlTableModel 动态加载数据 MVC「建议收藏」
CarSim仿真快速入门(十四)—CarSim-Simulink联合仿真
C语言学习日记3——realloc函数
[Infographics Show] 248 Public Domain Name
03 isomorphism of tree 1
Skiing mobile H5 game source code download