Android中文件的读写操作

1.读取SD卡中的文件,转换为byte[]类型,代码如下:
private byte[] File2Bytes(File file) {
int byte_size = 1024;
byte[] b = new byte[byte_size];
try {
FileInputStream fileInputStream = new FileInputStream(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(byte_size);
for (int length; (length = fileInputStream.read(b)) != -1;) {
outputStream.write(b, 0, length);
}
fileInputStream.close();
outputStream.close();
return outputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
2.将YUV格式的数据保存成Jpeg格式,代码如下:
/**
* 解析YUV数据并保存
*
* @param data
* @param camera
*/
private void saveYUVData(byte[] data, String fileName) {
YuvImage yuvImg = new YuvImage(data, ImageFormat.NV21, 960, 720, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvImg.compressToJpeg(new Rect(0, 0, 960, 720), 100, baos);
byte[] jdata = baos.toByteArray();
// 摄影画像取得
Bitmap bitmap = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
BitmapUtils.storeImage(mActivity, bitmap, fileName.substring(0, fileName.lastIndexOf(“.”)), false);
}

3.Bitmap的保存操作,代码如下:
public static boolean storeImage(Context context, Bitmap bmp, String picType, boolean isRotate) {
// 拍照按下时更新本次操作的年月日时分秒
String takenTime_YYMMDD_HHMMSS = new SimpleDateFormat(DATA_FORMAT).format(new Date());
String path = PIC_ROOT_PATH + picType + “.jpg”;
File f = new File(path);
if (f != null && !f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
if (isRotate) {
Matrix matrix = new Matrix();
matrix.reset();
matrix.postRotate(270);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
}
try {
FileOutputStream out = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), f.getAbsolutePath(), f.getName(), null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(“file://” + path)));
return true;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值