2013-12-18 47 views
10

正如標題所暗示的,我試圖讓我的Android應用程序的用戶從他的設備中選擇一個圖像(完成),然後我想縮小圖像(完成),將圖像壓縮/轉換爲png,然後將其作爲base64字符串發送到API。如何將位圖轉換爲PNG,然後轉換爲Android中的base64?

所以我目前調整圖像大小,像這樣:

options.inSampleSize = calculateInSampleSize(options, MAX_IMAGE_DIMENSION, MAX_IMAGE_DIMENSION); 
options.inJustDecodeBounds = false; 
Bitmap bitmap = BitmapFactory.decodeFile(path, options); 

我然後有一個位圖,我想轉換成PNG,並從那裏到Base64。我找到了一些示例代碼來轉換爲PNG並將其存儲在設備here上。

try { 
     FileOutputStream out = new FileOutputStream(filename); 
     bmp.compress(Bitmap.CompressFormat.PNG, 90, out); 
     out.close(); 
} catch (Exception e) { 
     e.printStackTrace(); 
} 

問題是我不想保存圖像。我只是想將它作爲PNG保存在內存中,然後將它進一步轉換爲base64字符串。

有沒有人知道我可以如何將圖像轉換爲PNG並將其存儲在變量中,或者甚至更好地將其轉換爲base64?歡迎所有提示!

回答

19

嘗試使用此方法的位圖轉換成PNG:

bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream); 

檢查method's documentation

您可以直接將位圖轉換爲Base64。用它來編碼和解碼Base64。

public static String encodeToBase64(Bitmap image) 
{ 
    Bitmap immagex=image; 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
    byte[] b = baos.toByteArray(); 
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT); 

    Log.e("LOOK", imageEncoded); 
    return imageEncoded; 
} 

public static Bitmap decodeBase64(String input) 
{ 
    byte[] decodedByte = Base64.decode(input, 0); 
    return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); 
} 
相關問題