Android基础实战之调用摄像头与相册 | 带实例

调用摄像头与相册

  • 调用摄像头拍照/从相册选择照片
  • xml

设置了两个按钮,分别是打开摄像头的按钮,以及打开相册的按钮

<Button
	        android:id="@+id/take_photo"
	        android:layout_width="222dp"
	        android:layout_height="50dp"
	        android:layout_marginTop="172dp"
	        android:onClick="takePhoto"
	        android:text="@string/take_photo"
	        app:layout_constraintEnd_toEndOf="parent"
	        app:layout_constraintHorizontal_bias="0.497"
	        app:layout_constraintStart_toStartOf="parent"
	        app:layout_constraintTop_toTopOf="parent" />

<Button
	        android:id="@+id/choose_from_album"
	        android:layout_width="222dp"
	        android:layout_height="50dp"
	        android:onClick="choosePhoto"
	        android:text="@string/choose_photo"
	        app:layout_constraintEnd_toEndOf="parent"
	        app:layout_constraintHorizontal_bias="0.497"
	        app:layout_constraintStart_toStartOf="parent"
	        app:layout_constraintTop_toBottomOf="@+id/take_photo" />

<ImageView
	        android:id="@+id/get_imageView"
	        android:layout_width="318dp"
	        android:layout_height="279dp"
	        android:layout_marginBottom="104dp"
	        app:layout_constraintBottom_toBottomOf="parent"
	        app:layout_constraintEnd_toEndOf="parent"
	        app:layout_constraintHorizontal_bias="0.494"
	        app:layout_constraintStart_toStartOf="parent"
	        app:layout_constraintTop_toBottomOf="@+id/choose_from_album"
	        app:layout_constraintVertical_bias="0.292"
	        android:contentDescription="@string/just_a_picture" />
  • MainActivity
public class MainActivity extends AppCompatActivity {

    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;
    private ImageView picture;
    private Uri imageUri;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        picture = findViewById(R.id.get_imageView);

    }

    public void takePhoto(View view) {

        // 创建File对象,用于存储拍照后的图片,将之存放在手机SD卡的应用关联缓存目录下
        // 调用getExternalCacheDir()方法可以得到该目录
        File outputImage = new File(getExternalCacheDir(),"output_image.jpg");

        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 进行判断,如果运行设备版本低于Android 7.0就调用Uri的fromFile()方法将File对象转换成Uri对象
        // 否则,就调用FileProvider的getUriForFile()方法将File对象转换成一个封装过的Uri对象
        // 该方法接收三个参数,第一个要求为Context对象,第二个为任意字符串,第三为刚创建的File对象
        // FileProvider是一种特殊的内容提供器,可以选择性地将封装过的Uri共享给外部,从而提高的应用的安全性
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(MainActivity.this,"com.example.cameraalbumtest.fileprovider",outputImage);

        } else {
            imageUri = Uri.fromFile(outputImage);
        }

        // 启动相机程序
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        startActivityForResult(intent,TAKE_PHOTO);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, 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;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    // 判断手机版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        // 4.4及以上系统使用这个方法处理图片
                        assert data != null;
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);
                    }
                }
            default:
                break;
        }
    }



    public void choosePhoto(View view) {

        // 在点击事件里动态申请WRITE_EXTERNAL_STORAGE这个危险权限。表示同时授予程序对SD卡读和写的能力
        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 denied the permission",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }

    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {

        String imagePath = null;
        Uri uri = data.getData();

        if (DocumentsContract.isDocumentUri(this,uri)) {
            // 如果是document类型的Uri,则通过document的id处理
            String docId = DocumentsContract.getDocumentId(uri);
            assert uri != null;
            // 如果Uri的authority是meida的格式的话,document需要再进行一次解析,通过字符串分割的方式取出真正的数字id
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                // 解析出数字格式的id
                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.parseLong(docId));
                imagePath = getImagePath(contentUri,null);
            }

        } else {
            assert uri != null;
            if ("content".equalsIgnoreCase(uri.getScheme())) {
                // 如果是content类型的uri,则使用普通方式
                imagePath = getImagePath(uri,null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                // 如果是file类型的uri,直接获取图片路径即可
                imagePath = uri.getPath();
            }
        }
        displayImage(imagePath);

    }

    private void handleImageBeforeKitKat(Intent data) {

        Uri uri = data.getData();
        String imagePath = getImagePath(uri,null);
        displayImage(imagePath);

    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        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 displayImage(String imagePath) {

        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            picture.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this,"failed to get image",Toast.LENGTH_SHORT).show();
        }
    }

}
  • Manifest.xml

添加了一个内容提供器,在其内部使用了<meta-data>来指定Uri的共享路径

以及申请权限

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

		<application
		    android:requestLegacyExternalStorage="true"
		    android:allowBackup="true"
		    android:icon="@mipmap/ic_launcher"
		    android:label="@string/app_name"
		    android:roundIcon="@mipmap/ic_launcher_round"
		    android:supportsRtl="true"
		    android:theme="@style/AppTheme"
		    tools:targetApi="q">
		    <activity android:name=".MainActivity">
		        <intent-filter>
		            <action android:name="android.intent.action.MAIN" />

		            <category android:name="android.intent.category.LAUNCHER" />
		        </intent-filter>
		    </activity>

		    <provider
		        android:authorities="com.example.cameraalbumtest.fileprovider"
		        android:name="androidx.core.content.FileProvider"
		        android:exported="false"
		        android:grantUriPermissions="true">

		        <meta-data
		            android:name="android.support.FILE_PROVIDER_PATHS"
		            android:resource="@xml/file_paths"/>

		    </provider>

		</application>
  • file_paths.xml

在res下面新建一个文件夹xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    	<external-path
        		name="my_images"
        		path=""/>
</paths>
  • 下载地址

DoSomeAndroidTest/CameraAlbumTest at main · qricis/DoSomeAndroidTest · GitHub

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值