安卓开发———打开相机拍照或者打开相册选择照片并显示出来

本文介绍了如何在Android应用中实现打开相机拍照和从相册选择照片的功能。首先展示了布局代码和事件绑定,接着详细讲解了启动相机及处理`onActivityResult`回调的过程。此外,还提到了在Manifest中注册`FileProvider`,以及处理4.4以上版本选取相册图片的差异。最后,文章提供了图片显示和压缩的方法。
摘要由CSDN通过智能技术生成

打开相机

测试UI

布局代码

<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中提供一系
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值