Android通过按钮点击调用相机拍照并获取图片方法

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.权限问题
调用相机拍摄图片和保存图片需要进行权限的授予,由于权限问题与安卓版本有关在此不再详解只做提醒。
 

posted on 2020-09-06 19:43  LaughMe  阅读(4604)  评论(0编辑  收藏  举报