转换成base64格式字符串和base64字符串转成bitmap

时间:2022-06-11 21:49:18
/**
* 将bitmap转换成base64格式字符串
*
* @param bitmap
* @return
*/
public static String bitmaptoString(Bitmap bitmap) {
// BitmapFactory.Options option = new BitmapFactory.Options();
// //option.inSampleSize =4; // 将图片设为原来宽高的1/4,防止内存溢出
// option.inJustDecodeBounds = true;
// Bitmap bitmap = BitmapFactory.decodeFile(imageUrL, option);
// 将Bitmap转换成Base64字符串
StringBuffer string = new StringBuffer();
ByteArrayOutputStream bStream = new ByteArrayOutputStream();

try {
bitmap.compress(CompressFormat.JPEG, 100, bStream);
bStream.flush();
bStream.close();
byte[] bytes = bStream.toByteArray();
string.append(Base64.encodeToString(bytes, Base64.NO_WRAP));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("string.." + string.length());
return string.toString();
}

/**
* 将url转换成base64格式字符串
*
* @param bitmap
* @return
*/
public static String urlToBitmapBase64(String url) {
BitmapFactory.Options option = new BitmapFactory.Options();
// option.inSampleSize =4; // 将图片设为原来宽高的1/4,防止内存溢出
Bitmap bitmap = BitmapFactory.decodeFile(url, option);
// 将Bitmap转换成Base64字符串
StringBuffer string = new StringBuffer();
ByteArrayOutputStream bStream = new ByteArrayOutputStream();

try {
bitmap.compress(CompressFormat.JPEG, 100, bStream);
bStream.flush();
bStream.close();
byte[] bytes = bStream.toByteArray();
string.append(Base64.encodeToString(bytes, Base64.NO_WRAP));
} catch (IOException e) {
e.printStackTrace();
}
LogUtil.d("TAG", "string.." + string.length());
return string.toString();
}

/**
* base64 String转成bitmap
*
* @param string
* @return
*/
public static Bitmap stringtoBitmap(String string) {
// 将字符串转换成Bitmap类型
Bitmap bitmap = null;
try {
byte[] bitmapArray;
bitmapArray = Base64.decode(string, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
}

return bitmap;
}