1: image图片转成base64
/**
* @param imgPath 图片地址
* @return String
*/
public static String imgToBase64(String imgPath) {
Bitmap bitmap = null;
if (imgPath !=null && imgPath.length() > 0) {
bitmap = readBitmap(imgPath);
}
if(bitmap == null){
Log.w("图片不存在","");
}
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
if(bitmap != null){
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
}
out.flush();
out.close();
byte[] imgBytes = out.toByteArray();
return Base64.encodeToString(imgBytes, Base64.DEFAULT);
} catch (Exception e) {
// TODO Auto-generated catch block
return null;
} finally {
try {
if(out != null) {
out.flush();
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static Bitmap readBitmap(String imgPath) {
try {
return BitmapFactory.decodeFile(imgPath);
} catch (Exception e) {
// TODO Auto-generated catch block
return null;
}
}
2: base64转成bitmap
/**
*
* @param base64Data base64
* @return Bitmap
*/
public static Bitmap stringToBitmap(String base64Data){
//将字符串转换成Bitmap类型
Bitmap bitmap=null;
try {
byte[] bitmapArray;
bitmapArray=Base64.decode(base64Data, Base64.DEFAULT);
bitmap=BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
3: drawable转成bitmap
/**
*
* @param Drawable
* @return Bitmap
*/
public static Bitmap drawableToBitmap( Drawable drawable){
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof NinePatchDrawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
} else {
return null;
}
}