1.调用照相机时通过putExtra的方式直接指定存储路径
String FilePath = "/sdcard/pic/";
File file = new File(FilePath);
file.mkdirs();// 创建文件夹
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 定义调用相机并取回图片的Intent意图
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(FilePath, "img.jpg"))); // 将图片保存到指定的存储路径
startActivityForResult(intent, 1);
onActivityResult方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Bitmap bitmap = BitmapFactory.decodeFile(FilePath + imgName);
ImageView ic = (ImageView) findViewById(R.id.imageView);
ic.setImageBitmap(bitmap);
} else {
finish();
}
}
2.在调用照相机后在onActivityResul里保存图片
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 定义调用相机并取回图片的Intent意图
startActivityForResult(intent, 1);
onActivityResult方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
File file = new File("/sdcard/pic/");
file.mkdirs();// 创建文件夹
String fileName = "/sdcard/pic/img.jpg";
try {
b = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件,其中第一个参数表示图片格式,
//第二个参数指压缩率。100表示不压缩
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
b.flush();
b.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ImageView ic = (ImageView) findViewById(R.id.imageView);
ic.setImageBitmap(bitmap);
} else {
finish();
}
}