2015-01-13 30 views
0

我正在開發一個Android應用程序,它需要一個位圖,將其轉換爲base64字符串並將其發送到後端,將其另存爲字符串。獲取所需的位圖寬度和高度以適應base64字符串

後端的大小限制大約爲1M,因此我需要在發送它之前在本地調整位圖大小,以確保base64字符串不會超過該限制。

是否有任何方式,公式等知道我必須調整位圖以獲得給定長度的base64字符串?

我目前正在遞歸地做這件事,但這顯然不是最好的解決方案。

段:

private void scaleImg(float scale) { 
    int newWidth = (int)(bmp.getWidth() * scale); 
    int newHeight = (int)(bmp.getHeight() * scale); 

    bmp = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true); 
    base64EncodedImg = PicUtils.convertBitmapToBase64String(bmp); 
    base64EncodedImgLength = base64EncodedImg.length(); 

    if(base64EncodedImgLength > 1000000) { 
     scaleImg(scale - 0.1f); 
    } 
} 

謝謝!

回答

0

Base64增加〜1.37x的字節數。

http://en.wikipedia.org/wiki/Base64

你也必須考慮你的尺寸計算的顏色字節。你不說圖像是如何編碼的(PicUtils.convertBitmapToBase64String()?)。我會假設32位顏色未壓縮(原始Android位圖字節)。

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test); 
    Pair<Integer,Integer> size = fitSize((int)Math.pow(10, 6),bitmap.getWidth(), bitmap.getHeight()); 
    bitmap = Bitmap.createScaledBitmap(bitmap, size.first, size.second, true); 
    byte[] bytes = getBitmapBytes(bitmap); 
    byte[] base64 = Base64.encode(bytes, Base64.DEFAULT); 

    Log.i("bitmapscaletest", "base 64 size: " + base64.length); 


    private Pair<Integer, Integer> fitSize(int size, int w, int h) { 
    double scale = 1.0; 
    while ((int)(w * h * 4 * 1.37) > size) { 
     scale -= 0.001; 
     w *= scale; 
     h *= scale; 
    } 
    return new Pair<Integer,Integer>(w, h); 
    } 

這比你所做的要好,因爲它實際上並沒有對每次迭代的位圖進行解碼/重新編碼。這可以被增強以進行二進制搜索。減小0.001以使尺寸接近10^6。

+0

這是有幫助的,但我仍然需要一個遞歸的方法,似乎吧? – Sandy

+0

其實這不是很有效。使用'float scale = MAX_IMG_SIZE_BASE64 /(5.48f * bmpWidth * bmpHeight);'我得到一個非常小的圖像。這可能是因爲編碼?我如何找到正在使用的編碼? – Sandy

+0

我正在使用'BitmapFactory.decodeFile(filename);'以前在代碼中獲取實際的位圖。 – Sandy