Android呼叫系統相機拍照並儲存到SD卡的兩種實現方式
阿新 • • 發佈:2019-02-17
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(); } }