打开相机
布局代码
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="打开相机"/>
<Button
android:id="@+id/chose_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="选择本地照片"/>
<ImageView
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
/>
获取控件并绑定事件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
take_photo=findViewById(R.id.take_photo);
chose_photo=findViewById(R.id.chose_photo);
picture=findViewById(R.id.picture);
take_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setTake_photo();
}
});
chose_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setChose_photo();
}
});
}
启动照相机
private void setTake_photo(){
//创建file对象储存拍摄到的照片,将图片命名为output_image.jpg,将他存储在sd卡的关联目录下,调用getExternalCacheDir()
//方法可以获得这个目录
File outputImg=new File(getExternalCacheDir(),"output_image.jpg");
try {
if (outputImg.exists()){
outputImg.delete();
}
outputImg.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
//判断系统版本,低于7.0会将file对象转换为uir对象否则调用getUriForFile将file对象转化为一个封装过的uir对象
//因为7.0开始直接使用本地真实路径会被认为是不安全的会抛出FileUirExposeption异常,FileProvider是一个
//内容提供器会将封装的uir提供给外部
if (Build.VERSION.SDK_INT>=24){
imgUri= FileProvider.getUriForFile(MainActivity.this,"com.example.cameraalbumtest.fileprovider",outputImg);
String adb=imgUri.toString();
}else {
imgUri=Uri.fromFile(outputImg);
}
Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
/* 先来说下intent的作用,intent是Android程序中各组件之间进行交互的一种重要方式,一般被用来启动活动、启动服务以及发送广播等;
intent在启动Activity的时候可以传递数据,比如说给另一个Activity传递数据,那么活动与活动之间是怎样进行数据传递的呢?
这时候就需要用到putExtra()方法。intent中提供一系