2012-03-19 25 views
63

のオブジェクトをエンコードしてデコードする必要があります。私はAndroid API10を使用していますAndroidのbase64文字列内のビットマップオブジェクトをエンコードしてデコードする

Bitmapをエンコードするためにこのフォームのメソッドを使用しようとしましたが、成功しませんでした。

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; 
} 

答えて

201
public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality) 
{ 
    ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream(); 
    image.compress(compressFormat, quality, byteArrayOS); 
    return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT); 
} 

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

使用例:それが取るビットマップにJPEGに変換されますよう

String myBase64Image = encodeToBase64(myBitmap, Bitmap.CompressFormat.JPEG, 100); 
Bitmap myBitmapAgain = decodeBase64(myBase64Image); 
+2

パーフェクト..ありがとう! – Noman

+2

ありがとうございます!これは、私が必要としていた、短くて甘いものです。 –

+5

コードは言葉以上のことを話します、ありがとう! – atx

9

(ビットマップを構築するためにURIを参照している場合)、これはあなたに

Bitmap bitmap = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(uri)); 

を助けることを願っています OR

Resources resources = this.getResources(); 
Bitmap bitmap= BitmapFactory.decodeResource(resources , R.drawable.logo); 

(ビットマップを構築するために描画可能を参照している場合)

次にエンコードする

ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); 
byte[] image = stream.toByteArray(); 
String encodedImage = Base64.encode(image, Base64.DEFAULT); 

デコードロジックは、正確にエンコーディングの逆れるため

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT); 
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
+0

私はBitmapFactoryを避けたいでしょうより多くの記憶。 jpeg/pngをbyte []に​​変換してBase64に変換するソリューションは、Androidsには最適です。 –

関連する問題