您的位置:首页 > 编程语言 > PHP开发

将文件转为byte[],通过ByteArrayOutputStream 实现

2016-05-05 09:34 477 查看

通过文件路径 转换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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: