base64图片格式的转换
1.bitmap的图片格式转为base64的图片格式:
public static String bitmapToBase64(Bitmap bitmap) {
String result = null;
ByteArrayOutputStream baos = null;
try {
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);
baos.flush();
baos.close();
byte[] bitmapBytes = baos.toByteArray();
result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.flush();
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
2.base64格式的图片转为Bitmap的格式:
public static Bitmap base64ToBitmap(String base64Data) {// base64转为Bitmap
byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bitmap;
}
3.base64格式的图片转为byte[]格式:
public static byte[] base64ToByte(String base64Data) {
byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
return bytes;
}
4.Url格式的图片转成base64格式的图片:
public static String getBase64Image(String ImageUrl) {
String result = null;
ByteArrayOutputStream baos = null;
try {
URL url = new URL(ImageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);
baos.flush();
baos.close();
byte[] bitmapBytes = baos.toByteArray();
result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
}
} else {
return null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (baos != null) {
try {
baos.flush();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}