2012-03-19 34 views
63

我想编码和解码Bitmap对象在字符串base64。我使用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); 
} 

实例:

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

完美..谢谢 – Noman 2013-11-17 12:42:48

+2

谢谢!这正是我所需要的,简短而甜美。 – 2014-01-31 22:24:49

+5

代码说话多于言语,谢谢! – atx 2014-12-11 10:19:01

9

希望这将帮助你

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

(如果您引用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转换为位图,其中将更多的记忆。任何将jpeg/png转换为byte []和Base64的解决方案都适用于Android。 – 2013-02-12 19:05:37