通过文件路径 转换byte[] 通过ByteArrayOutputStream 实现
/**
* 将文件转为byte[]
* @param filePath 文件路径
* @return
*/
public static byte[] getBytes(String filePath){
File file = new File(filePath);
ByteArrayOutputStream out = null;
try {
FileInputStream in = new FileInputStream(file);
out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int i = 0;
while ((i = in.read(b)) != -1) {
out.write(b, 0, b.length);
}
out.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] s = out.toByteArray();
return s;
}
将bitmap对象 转为byte[] 并进行Base64压缩
/**
* bitmap转为base64
*
* @param bitmap
* @return
*/
public static String bitmapToBase64(Bitmap bitmap) {
String result = null;
ByteArrayOutputStream baos = null;
try {
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, 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;
}
版权声明:本文为qq_31028313原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。