1.為按鈕設置點擊事件
Button btn1= (Button) findViewById(R.id.btn1);
//點擊按鈕觸發opencarema()方法
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
opencarema();
}
});
2.opencarema()方法
//此方法實現點擊按鈕彈出拍照界面
public void opencarema()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 2);
}
3.重寫onActivityResult方法
//此方法用於獲取拍得的圖片,並啟動saveScreenShot方法保存圖片
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2 && resultCode == RESULT_OK && null != data)
{
Bundle bundle = data.getExtras();
//獲取相機返回的數據,並轉換為Bitmap圖片格式,這是縮略圖
Bitmap bitmap = (Bitmap) bundle.get("data");
System.out.println("獲取圖像成功");
saveScreenShot(bitmap);
}
super.onActivityResult(requestCode, resultCode, data);
}
4.saveScreenShot方法
//此方法用於保存拍得的圖片,其中image_save_path因手機品牌不同有所差別,大多數為String image_save_path="/storage/emulated/0/DCIM/Camera/";
//之后就可以用picturePath來進一步對圖片進行操作
private void saveScreenShot(Bitmap bitmap) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
//以保存時間為文件名
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmss");
image_save_path = sdf.format(date);
File file = new File(extStorageDirectory, image_save_path+".JPEG");//創建文件,第一個參數為路徑,第二個參數為文件名
String picturePath=file.getPath();
try {
outStream = new FileOutputStream(file);//創建輸入流
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.close();
// 這三行可以實現相冊更新
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);intent.setData(uri);
sendBroadcast(intent);
} catch(Exception e) {
Toast.makeText(MainActivity.this, "exception:" + e,
Toast.LENGTH_SHORT).show();
}
}
5.權限問題
調用相機拍攝圖片和保存圖片需要進行權限的授予,由於權限問題與安卓版本有關在此不再詳解只做提醒。