在實際開發當中我們經常會忽視如題問題,只是知道圖片越小越好,甚至根本不知道如何計算,今天筆者就拋磚引玉一把!
Android中一張圖片(Bitmap)占用的內存主要和以下幾個因數有關:圖片長度,圖片寬度,單位像素占用的字節數。
計算方法:一張圖片(Bitmap)占用的內存=圖片長度*圖片寬度*單位像素占用的字節數
長度和寬度不用多做解釋 ,單位是像素;關鍵是單位像素占用的字節數如何獲得呢?
這里不得不提一下Bitmap創建的API
Bitmap bitmap = BitmapFactory.decodeResource(Resources res,int id,
BitmapFactory.Options opts);
單位像素占用的字節數由其參數BitmapFactory.Options的inPreferredConfig變量決定,默認為Bitmap.Config.ARGB_8888
inPreferredConfig為Bitmap.Config類型,
Bitmap.Config
類是個枚舉類型,它可以為以下值
ALPHA_8 | Each pixel is stored as a single translucency (alpha) channel. This is very useful to efficiently store masks for instance. No color information is stored. With this configuration, each pixel requires 1 byte of memory. 此時圖片只有alpha值,沒有RGB值,一個像素占用1個字節 |
ARGB_4444 | This field is deprecated. Because of the poor quality of this configuration, it is advised to use ARGB_8888 instead. 這種格式的圖片,看起來質量太差,已經不推薦使用。 Each pixel is stored on 2 bytes. The three RGB color channels and the alpha channel (translucency) are stored with a 4 bits precision (16 possible values.) This configuration is mostly useful if the application needs to store translucency information but also needs to save memory. It is recommended to use ARGB_8888 instead of this configuration. 一個像素占用2個字節,alpha(A)值,Red(R)值,Green(G)值,Blue(B)值各占4個bites,共16bites,即2個字節 |
ARGB_8888 | Each pixel is stored on 4 bytes. Each channel (RGB and alpha for translucency) is stored with 8 bits of precision (256 possible values.) This configuration is very flexible and offers the best quality. It should be used whenever possible 一個像素占用4個字節,alpha(A)值,Red(R)值,Green(G)值,Blue(B)值各占8個bites,共32bites,即4個字節 這是一種高質量的圖片格式,電腦上普通采用的格式。它也是Android手機上一個BitMap的默認格式。 |
RGB_565 | Each pixel is stored on 2 bytes and only the RGB channels are encoded: red is stored with 5 bits of precision (32 possible values), green is stored with 6 bits of precision (64 possible values) and blue is stored with 5 bits of precision. This configuration can produce slight visual artifacts depending on the configuration of the source. For instance, without dithering, the result might show a greenish tint. To get better results dithering should be applied. This configuration may be useful when using opaque bitmaps that do not require high color fidelity. 一個像素占用2個字節,沒有alpha(A)值,即不支持透明和半透明,Red(R)值占5個bites ,Green(G)值占6個bites ,Blue(B)值占5個bites,共16bites,即2個字節.對於沒有透明和半透明顏色的圖片來說,該格式的圖片能夠達到比較的呈現效果,相對於ARGB_8888來說也能減少一半的內存開銷。因此它是一個不錯的選擇。另外我們通過android.content.res.Resources來取得一個張圖片時,它也是以該格式來構建BitMap的. 從Android4.0開始,該選項無效。即使設置為該值,系統任然會采用 ARGB_8888來構造圖片 |
所以一張100px*100px的圖片在內存中占用的內存數為:
圖片格式 | 計算公式 | 占用內存大小 |
ALPHA_8 | 100*100 | 10000b |
ARGB_4444 | 100*100*2 | 20000b |
ARGB_8888 | 100*100*4 | 40000b |
RGB_565 | 100*100*2 | 20000b |
綜上就是今天筆者要分享的小知識,一般這樣的問題面試官會問。你get到了嗎?