一張Bitmap圖片可以壓縮成多大內存

Android裏面加載大圖片的話很容易引起內存溢出,out of memory,因爲如果你如果把一張很大的原圖加載到ImageView的話,會提示
這裏寫圖片描述
一張圖片在內存中佔有多大呢,Bitmap有個函數可以直接獲取內存中佔有的大小。我們看下Bitmap類裏面

 /**
     * Returns the minimum number of bytes that can be used to store this bitmap's pixels.
     *
     * <p>As of {@link android.os.Build.VERSION_CODES#KITKAT}, the result of this method can
     * no longer be used to determine memory usage of a bitmap. See {@link
     * #getAllocationByteCount()}.</p>
     */
    public final int getByteCount() {
        if (mRecycled) {
            Log.w(TAG, "Called getByteCount() on a recycle()'d bitmap! "
                    + "This is undefined behavior!");
            return 0;
        }
        // int result permits bitmaps up to 46,340 x 46,340
        return getRowBytes() * getHeight();
    }

其中getRowBytes()是獲取一行像素的內存大小。我們可以用getByteCount來獲取圖片的大小。比如我們項目裏放一張10M的圖片,然後執行getByteCount(),然後將大小打印出來。
如果要自己手算的話,也是可以算的,不過比較麻煩:
這裏寫圖片描述
當圖片以格式ARGB_8888存儲時的計算方式

佔用內存=圖片長*圖片寬*4字節

圖片長 = 圖片原始長 (設備DPI/文件夾DPI)
圖片寬 = 圖片原始寬(設備DPI/文件夾DPI)
好了。
比如我這張圖片的大小如果是9318427byte的話(暫時還想不到辦法得到一張完整10兆的圖片,只能近似地取了一張9M多的圖片)。那麼執行函數的到的大小是162739584 325479168 當前的設備dpi爲420,文件夾是mdpi,也就是240.然後算一下, (420/240)* (3968*2976)* 4= 82661376 byte 。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章