在Android中对base64string中的位图对象进行编码和解码

我想要在stringbase64编码和解码Bitmap对象。 我使用Android API10,

我试过,没有成功,使用这种forms的方法来编码一个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; } 
 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); 

希望对你有帮助

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

(如果你正在引用URI来构造位图)

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

(如果你引用drawable来构造位图)

然后编码

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