《第一行代码Android》学习总结第八章 使用摄像头与相册

一、调用摄像头拍照

1、新建CameraAlbumTest项目,修改activity_main.xml文件,添加一个Button用于打开摄像头进行拍照,添加ImageView用于将图片显示出来。

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <Button
      android:id="@+id/take_photo"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="take photo"/>
    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>
</LinearLayout>

2、修改MainActivity中代码。

public class MainActivity extends AppCompatActivity {
    public static final int TAKE_PHOTO = 1;
private ImageView picture;
//图片本地的真实路径
    private Uri imageUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button takePhoto = (Button) findViewById(R.id.take_photo);
        picture = (ImageView) findViewById(R.id.picture);
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//用于存放拍下的照片
                File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
                try {
                    if(outputImage.exists()){
                       outputImage.delete();
                    }
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(Build.VERSION.SDK_INT >= 24){
//File对象转换为Uri标识对象
                    imageUri = FileProvider.getUriForFile(MainActivity.this, "com.launcher.cameraalbumtest.fileprovider", outputImage);
                }else{
//指定图片的输出地址
                    imageUri = Uri.fromFile(outputImage);
                }
//隐式Intent,启动相机程序
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, TAKE_PHOTO);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case TAKE_PHOTO:
                if(resultCode == RESULT_OK){
                    try {
//拍照成功后显示图片
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }
}

应用关联缓存目录:

        SD卡中专门用于存放当前应用缓存数据的位置,调用getExternalCacheDir()方法可以得到这个目录,具体路径:/sdcard/Android/data/<package name>/cache。

        Android 6.0以后读写SD卡被列为危险权限,如果将图片存放到其他目录要进行运行时权限处理,使用应用关联缓存目录可以跳过这一步。

        Android 7.0以后,直接使用本地真实路径的Uri被认为是不安全的,会抛出FileUriExposedException异常,而使用FileProvider是一种特殊的内容提供器,它使用了和内容提供器类似的机制对数据进行保护,可以选择性的封装过的Uri共享给外部,从而提高应用的安全性。

3、在AndroidManifest中修改代码,注册内容提供器。

<provider
      android:authorities="com.launcher.cameraalbumtest.fileprovider"
      android:name="android.support.v4.content.FileProvider"
      android:exported="false"
      android:grantUriPermissions="true">
      <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths"/>
</provider>

        <meta-data/>用于指定Uri共享路径

        其中android:authorities属性必须与FileProvider.getUriForFile()方法中第二个参数一致。

4、右击res目录→New→Directory,创建一个xml目录,右击xml目录→New→File,创建file_path.xml文件。

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_image" path=""/>
</paths>

<external-path/>用于指定Uri共享。

name属性可以随便填。

path属性表示共享的具体路径。设置空值表示将整个SD卡进行共享。

5、加入权限声明

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

从相册中选择照片

1、在上一节CameraAlbumTest项目基础上修改。

2、修改activity_main.xml文件,添加一个Button用于从相册中选择照片。

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <Button
      android:id="@+id/take_photo"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="take photo"/>
  <Button
      android:id="@+id/choose_from_album"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="Choose From Album"/>
    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>
</LinearLayout>

3、修改MainActivity代码。

public class MainActivity extends AppCompatActivity {
    ……
    public static final int CHOOSE_PHOTO = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button takePhoto = (Button) findViewById(R.id.take_photo);
        Button chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);
        ……
        chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//运行时权限处理
                if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(MainActivity.this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);
                }else{
                    openAlbum();
                }
            }
        });
    }

private void openAlbum() {
//隐式Intent
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                }
                else{
                    Toast.makeText(this, "You deny the permission", Toast.LENGTH_LONG).show();
                }
                break;
            default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            ……
            case CHOOSE_PHOTO:
                if(resultCode == RESULT_OK){
//判断手机版本号
                    if(Build.VERSION.SDK_INT >= 19){
                        handleImageOnKitKat(data);
                    }else{
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }
//解析封装过的Uri,android4.4以后选取相册中图片不再返回图片真实的Uri,而是封装过的Uri
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if(DocumentsContract.isDocumentUri(this, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads//public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        }else if("content".equalsIgnoreCase(uri.getScheme())){
                imagePath = getImagePath(uri,null);
        }else if("file".equalsIgnoreCase(uri.getScheme())){
                imagePath = uri.getPath();
            }
        displayImage(imagePath);
    }

    private void displayImage(String imagePath) {
        if(imagePath != null){
//显示选中的图片
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            picture.setImageBitmap(bitmap);
        }else{
            Toast.makeText(this, "failed to get image", Toast.LENGTH_LONG).show();
        }
    }
//通过ContentResolver查询相册中的数据
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if(cursor != null){
            if(cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }
}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值