這是拍照反圖片以及相機反圖片的簡單實例
小白上路先實現效果再談原理~
這里我就先不寫思路了,直接上效果圖,哪里不懂的留言即可。
效果

image.png
步驟1、權限(清單文件添加)
<!--拍照-->
<uses-permission android:name="android.permission.CAMERA" />
<!--讀寫-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.PERMISSIONS_STORAGE"/>
步驟2、res文件夾下邊創(chuàng)建xml文件file_paths.xml命名
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<!--files-path 相當于 getFilesDir()-->
<files-path name="my_images" path="images"/>
<!--cache-path 相當于 getCacheDir()-->
<cache-path name="lalala" path="cache_image"/>
<!--external-path 相當于 Environment.getExternalStorageDirectory()-->
<external-path name="hahaha" path="comeOn"/>
<!--external-files-path 相當于 getExternalFilesDir("") -->
<external-files-path name="paly" path="freeSoft"/>
<!--external-cache-path 相當于 getExternalCacheDir() -->
<external-cache-path name="lei" path="."/>
</paths>
步驟3、配置清單文件
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.mooc.uploadfile4.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
tools:ignore="MissingClass">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>

image.png
步驟4、布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/camera_bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="相機" />
<Button
android:id="@+id/photo_bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="相冊" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:gravity="center"
android:text="以下是展示相機拍照返回的圖片" />
<ImageView
android:id="@+id/camere_iv"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="6dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:gravity="center"
android:text="以下是展示相冊拍照返回的圖片" />
<ImageView
android:id="@+id/photo_iv"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="6dp" />
</LinearLayout>

image.png
步驟5、MainActivity代碼
package com.mooc.uploadfile4;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button cameraBt;
private Button photoBt;
private ImageView camereIv;
private ImageView photoIv;
private String TAG = "tag";
//需要的權限數組 讀/寫/相機
private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//跳轉相機動態(tài)權限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}
initView();
}
private Uri ImageUri;
public static final int TAKE_PHOTO = 101;
public static final int TAKE_CAMARA = 100;
private void initView() {
cameraBt = (Button) findViewById(R.id.camera_bt);
photoBt = (Button) findViewById(R.id.photo_bt);
camereIv = (ImageView) findViewById(R.id.camere_iv);
photoIv = (ImageView) findViewById(R.id.photo_iv);
cameraBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//檢查是否已經獲得相機的權限
if (verifyPermissions(MainActivity.this, PERMISSIONS_STORAGE[2]) == 0) {
Log.i(TAG, "提示是否要授權");
ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS_STORAGE, 3);
} else {
//已經有權限
toCamera(); //打開相機
}
}
});
photoBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toPicture();
}
});
}
@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));
camereIv.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
case TAKE_CAMARA:
if (resultCode == RESULT_OK) {
try {
//將相冊的照片顯示出來
Uri uri_photo = data.getData();
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri_photo));
photoIv.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
/**
* 檢查是否有對應權限
*
* @param activity 上下文
* @param permission 要檢查的權限
* @return 結果標識
*/
public int verifyPermissions(Activity activity, java.lang.String permission) {
int Permission = ActivityCompat.checkSelfPermission(activity, permission);
if (Permission == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "已經同意權限");
return 1;
} else {
Log.i(TAG, "沒有同意權限");
return 0;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "用戶授權");
toCamera();
} else {
Log.i(TAG, "用戶未授權");
}
}
//跳轉相冊
private void toPicture() {
Intent intent = new Intent(Intent.ACTION_PICK); //跳轉到 ACTION_IMAGE_CAPTURE
intent.setType("image/*");
startActivityForResult(intent, TAKE_CAMARA);
Log.i(TAG, "跳轉相冊成功");
}
//跳轉相機
private void toCamera() {
//創(chuàng)建File對象,用于存儲拍照后的圖片
// File outputImage = new File(getExternalCacheDir(), "outputImage.jpg");
File outputImage = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
if (outputImage.exists()) {
outputImage.delete();
} else {
try {
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//判斷SDK版本高低,ImageUri方法不同
if (Build.VERSION.SDK_INT >= 24) {
ImageUri = FileProvider.getUriForFile(MainActivity.this, "com.mooc.uploadfile4.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);
}
}