将image.jpg转换为Base64字符串

时间:2016-02-20 06:45:20

标签: android

错误日志是image:null

我的问题不正确将图片转换为base64。

我的代码编码图像

BitmapDrawable drawable = (BitmapDrawable) ivProfilePic.getDrawable();   
Bitmap bitmap = drawable.getBitmap(); 
ByteArrayOutputStream bos = new ByteArrayOutputStream();       
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bos); byte[] bb = bos.toByteArray();
String encodedString = Base64.encodeToString(bb,Base64.DEFAULT);
Log.d("ImageBase34", encodedString);

解码字符串以隐藏图像

byte[] decodedString = Base64.decode(userDetailBean.getProfile_picture().getBytes(), Base64.DEFAULT);
Bitmap base64Bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Log.d("img", String.valueOf(base64Bitmap));
ivProfilePic.setImageBitmap(base64Bitmap);

1 个答案:

答案 0 :(得分:0)

使用 encodedString 作为Base64.decode()方法中的第一个参数,而不是 userDetailBean.getProfile_picture()

您需要像这样更改代码。

BitmapDrawable drawable = (BitmapDrawable) getDrawable(R.drawable.ic_default_user);
Bitmap bitmap = drawable.getBitmap();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bos); byte[] bb = bos.toByteArray();
encodedString = Base64.encodeToString(bb,Base64.DEFAULT);
Log.d("ImageBase34", encodedString);

解码字符串以隐藏图像

byte[] decodedString = Base64.decode(encodedString, Base64.DEFAULT);
Bitmap base64Bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Log.d("img", String.valueOf(base64Bitmap));
imageView.setImageBitmap(base64Bitmap);
相关问题