App下載

android怎么進(jìn)行拍照和取出相冊(cè)圖片?android實(shí)現(xiàn)拍照或從相冊(cè)選取圖片方法分享!

重度健忘癥患者 2021-08-20 16:31:19 瀏覽數(shù) (7225)
反饋

在生活不斷的富裕中我們對(duì)于身邊的事情都喜歡用手機(jī)拍照記錄自己的每個(gè)時(shí)刻,那么今天我們就來(lái)講下有關(guān)于“android怎么進(jìn)行拍照和取出相冊(cè)圖片?”這個(gè)問(wèn)題的解決方法和相關(guān)內(nèi)容分享!

獲取圖片方式: (類(lèi)似更換頭像的效果)

1、手機(jī)拍照 選擇圖片;
2、相冊(cè)選取圖片;

本文只是簡(jiǎn)單實(shí)現(xiàn)該功能,頁(yè)面展示有些簡(jiǎn)陋,運(yùn)行效果圖如下:

創(chuàng)建xml布局文件(activity_main.xml ): 頭部?jī)蓚€(gè)Button按鈕,一個(gè)控制從相冊(cè)選擇照片,一個(gè)控制啟動(dòng)相冊(cè)拍照選擇圖片。底部為一個(gè)ImageVIew,用于展示剛剛選擇的圖片。

<?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"
 android:padding="16dp"
 tools:context=".MainActivity">
 
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content">
 
 <Button
 android:id="@+id/btn_photo"
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:background="@android:color/holo_red_light"
 android:text="相冊(cè)選取"
 android:textColor="#FFF"
 android:textSize="16sp" />
 
 <Button
 android:id="@+id/btn_camera"
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_marginLeft="16dp"
 android:layout_weight="1"
 android:background="@android:color/holo_red_light"
 android:text="拍照"
 android:textColor="#FFF"
 android:textSize="16sp" />
 </LinearLayout>
 
 <!--展示選擇的圖片-->
 <ImageView
 android:id="@+id/image_show"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_gravity="center_horizontal"
 android:layout_margin="6dp" />
 
</LinearLayout>

Android 4.4系統(tǒng)之前, 訪問(wèn)SD卡的應(yīng)用關(guān)聯(lián)目錄需要聲明權(quán)限的,從4.4系統(tǒng)開(kāi)始不再需要權(quán)限聲明。相關(guān)權(quán)限變成動(dòng)態(tài)申請(qǐng)。

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

第一部分:拍照獲取圖片

我們將拍照的圖片放在SD卡關(guān)聯(lián)緩存目錄下。調(diào)用getExternalCacheDir()方法得到關(guān)聯(lián)緩存目錄, 具體的路徑是/sdcard/Android/data/<package name>/cache。 那么為什么要使用應(yīng)用關(guān)聯(lián)緩目錄來(lái)存放圖片呢?因?yàn)閺腁ndroid 6.0系統(tǒng)開(kāi)始, 讀寫(xiě)SD卡被列為了危險(xiǎn)權(quán)限, 如果將圖片存放在SD卡的任何其他目錄, 都要進(jìn)行運(yùn)行時(shí)權(quán)限處理, 使用應(yīng)用關(guān)聯(lián)
目錄則可以跳過(guò)這一步。

**
 * 拍照 或 從相冊(cè)獲取圖片
 */
public class MainActivity extends AppCompatActivity {
 private Button btn_camera;
 private ImageView imageView;
 
 public static final int TAKE_CAMERA = 101;
 private Uri imageUri;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 btn_camera = (Button) findViewById(R.id.btn_camera);
 imageView = (ImageView) findViewById(R.id.image_show);
 
 //通過(guò)攝像頭拍照
 btn_camera.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 // 創(chuàng)建File對(duì)象,用于存儲(chǔ)拍照后的圖片
 //存放在手機(jī)SD卡的應(yīng)用關(guān)聯(lián)緩存目錄下
 File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
 /* 從Android 6.0系統(tǒng)開(kāi)始,讀寫(xiě)SD卡被列為了危險(xiǎn)權(quán)限,如果將圖片存放在SD卡的任何其他目錄,
 都要進(jìn)行運(yùn)行時(shí)權(quán)限處理才行,而使用應(yīng)用關(guān)聯(lián) 目錄則可以跳過(guò)這一步
 */
 try {
 if (outputImage.exists()) {
 outputImage.delete();
 }
 } catch (Exception e) {
 e.printStackTrace();
 }
 /*
 7.0系統(tǒng)開(kāi)始,直接使用本地真實(shí)路徑的Uri被認(rèn)為是不安全的,會(huì)拋 出一個(gè)FileUriExposedException異常。
 而FileProvider則是一種特殊的內(nèi)容提供器,它使用了和內(nèi) 容提供器類(lèi)似的機(jī)制來(lái)對(duì)數(shù)據(jù)進(jìn)行保護(hù),
 可以選擇性地將封裝過(guò)的Uri共享給外部,從而提高了 應(yīng)用的安全性
 */
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 //大于等于版本24(7.0)的場(chǎng)合
 imageUri = FileProvider.getUriForFile(MainActivity.this, "com.feige.pickphoto.fileprovider", outputImage);
 } else {
 //小于android 版本7.0(24)的場(chǎng)合
 imageUri = Uri.fromFile(outputImage);
 }
 
 //啟動(dòng)相機(jī)程序
 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 //MediaStore.ACTION_IMAGE_CAPTURE = android.media.action.IMAGE_CAPTURE
 intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
 startActivityForResult(intent, TAKE_CAMERA);
 
 }
 });
 
 @Override
 protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
 switch (requestCode) {
 case TAKE_CAMERA:
 if (resultCode == RESULT_OK) {
 try {
 // 將拍攝的照片顯示出來(lái)
 Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
 imageView.setImageBitmap(bitmap);
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 }
 }
 break;
 default:
 break;
 }
 }
}

從Android 7.0開(kāi)始, 直接使用本地真實(shí)路徑的Uri被認(rèn)為是不安全的, 會(huì)拋出一個(gè)FileUriExposedException異常。 FileProvider則是一種特殊的內(nèi)容提供器, 它使用了和內(nèi)容提供器類(lèi)似的機(jī)制來(lái)對(duì)數(shù)據(jù)進(jìn)行保護(hù), 可以選擇性地將封裝過(guò)的Uri共享給外部, 從而提高了應(yīng)用的安全性。

首先要在AndroidManifest.xml中對(duì)內(nèi)容提供器進(jìn)行注冊(cè)了:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.feige.pickphoto">
 
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 
 <application
 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">
 <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:name="android.support.v4.content.FileProvider"
 android:authorities="com.feige.pickphoto.fileprovider"
 android:exported="false"
 android:grantUriPermissions="true">
 <meta-data
 android:name="android.support.FILE_PROVIDER_PATHS"
 android:resource="@xml/file_paths" />
 </provider>
 
 </application>
 
</manifest>

創(chuàng)建file_paths 資源文件:在res目錄上右擊——> new ——> Directory創(chuàng)建xml文件夾,然后在xml文件夾里新建file_paths.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
 <!--external-path 就是用來(lái)指定Uri 共享的,
 name 屬性的值可以隨便填, path 屬性的 值表示共享的具體路徑。
 這里設(shè)置 . 就表示將整個(gè)SD卡進(jìn)行共享 -->
 <external-path
 name="my_images"
 path="." />
</paths>

第二部分:從相冊(cè)獲取圖片

/**
 * 拍照 或 從相冊(cè)獲取圖片
 */
public class MainActivity extends AppCompatActivity {
 private Button choose_photo;
 private ImageView imageView;
 
 public static final int PICK_PHOTO = 102;
 private Uri imageUri;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 choose_photo = (Button) findViewById(R.id.btn_photo);
 imageView = (ImageView) findViewById(R.id.image_show); 
 
 //從相冊(cè)選擇圖片
 choose_photo.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 //動(dòng)態(tài)申請(qǐng)獲取訪問(wèn) 讀寫(xiě)磁盤(pán)的權(quán)限
 if (ContextCompat.checkSelfPermission(MainActivity.this,
 Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
 } else {
 //打開(kāi)相冊(cè)
 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
 //Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
 intent.setType("image/*");
 startActivityForResult(intent, PICK_PHOTO); // 打開(kāi)相冊(cè)
 }
 }
 });
 }
 
 @Override
 protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
 switch (requestCode) {
 case PICK_PHOTO:
 if (resultCode == RESULT_OK) { // 判斷手機(jī)系統(tǒng)版本號(hào)
 if (Build.VERSION.SDK_INT >= 19) {
 // 4.4及以上系統(tǒng)使用這個(gè)方法處理圖片
 handleImageOnKitKat(data);
 } else {
 // 4.4以下系統(tǒng)使用這個(gè)方法處理圖片
 handleImageBeforeKitKat(data);
 }
 }
 
 break;
 default:
 break;
 }
 }
 
 @TargetApi(19)
 private void handleImageOnKitKat(Intent data) {
 String imagePath = null;
 Uri uri = data.getData();
 if (DocumentsContract.isDocumentUri(this, uri)) {
 // 如果是document類(lèi)型的Uri,則通過(guò)document id處理
 String docId = DocumentsContract.getDocumentId(uri);
 if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
 String id = docId.split(":")[1];
 // 解析出數(shù)字格式的id
 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())) {
 // 如果是content類(lèi)型的Uri,則使用普通方式處理
 imagePath = getImagePath(uri, null);
 } else if ("file".equalsIgnoreCase(uri.getScheme())) {
 // 如果是file類(lèi)型的Uri,直接獲取圖片路徑即可
 imagePath = uri.getPath();
 }
 // 根據(jù)圖片路徑顯示圖片
 displayImage(imagePath);
 }
 
 /**
 * android 4.4以前的處理方式
 * @param data
 */
 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;
 // 通過(guò)Uri和selection來(lái)獲取真實(shí)的圖片路徑
 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);
 imageView.setImageBitmap(bitmap);
 } else {
 Toast.makeText(this, "獲取相冊(cè)圖片失敗", Toast.LENGTH_SHORT).show();
 }
 }
 
}

共用拍照取圖的FileProvider內(nèi)容提供器。 

*********完整MainActivity代碼:

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
 
import java.io.File;
import java.io.FileNotFoundException;
 
/**
 * 拍照 或 從相冊(cè)獲取圖片
 */
public class MainActivity extends AppCompatActivity {
 private Button choose_photo;
 private Button btn_camera;
 private ImageView imageView;
 
 public static final int TAKE_CAMERA = 101;
 public static final int PICK_PHOTO = 102;
 private Uri imageUri;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 choose_photo = (Button) findViewById(R.id.btn_photo);
 btn_camera = (Button) findViewById(R.id.btn_camera);
 imageView = (ImageView) findViewById(R.id.image_show);
 
 //通過(guò)攝像頭拍照
 btn_camera.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 // 創(chuàng)建File對(duì)象,用于存儲(chǔ)拍照后的圖片
 //存放在手機(jī)SD卡的應(yīng)用關(guān)聯(lián)緩存目錄下
 File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
 /** 從Android 6.0系統(tǒng)開(kāi)始,讀寫(xiě)SD卡被列為了危險(xiǎn)權(quán)限,如果將圖片存放在SD卡的任何其他目錄,
 *都要進(jìn)行運(yùn)行時(shí)權(quán)限處理才行,而使用應(yīng)用關(guān)聯(lián) 目錄則可以跳過(guò)這一步
 */
 try {
 if (outputImage.exists()) {
 outputImage.delete();
 }
 } catch (Exception e) {
 e.printStackTrace();
 }
 
 /**
 *7.0系統(tǒng)開(kāi)始,直接使用本地真實(shí)路徑的Uri被認(rèn)為是不安全的,會(huì)拋 出一個(gè)FileUriExposedException異常。
 *而FileProvider則是一種特殊的內(nèi)容提供器,它使用了和內(nèi) 容提供器類(lèi)似的機(jī)制來(lái)對(duì)數(shù)據(jù)進(jìn)行保護(hù),
 *可以選擇性地將封裝過(guò)的Uri共享給外部,從而提高了 應(yīng)用的安全性
 */
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 //大于等于版本24(7.0)的場(chǎng)合
 imageUri = FileProvider.getUriForFile(MainActivity.this, "com.feige.pickphoto.fileprovider", outputImage);
 } else {
 //小于android 版本7.0(24)的場(chǎng)合
 imageUri = Uri.fromFile(outputImage);
 }
 
 //啟動(dòng)相機(jī)程序
 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 //MediaStore.ACTION_IMAGE_CAPTURE = android.media.action.IMAGE_CAPTURE
 intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
 startActivityForResult(intent, TAKE_CAMERA);
 
 }
 });
 
 //從相冊(cè)選擇圖片
 choose_photo.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 //動(dòng)態(tài)申請(qǐng)獲取訪問(wèn) 讀寫(xiě)磁盤(pán)的權(quán)限
 if (ContextCompat.checkSelfPermission(MainActivity.this,
 Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
 ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
 } else {
 //打開(kāi)相冊(cè)
 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
 //Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
 intent.setType("image/*");
 startActivityForResult(intent, PICK_PHOTO); // 打開(kāi)相冊(cè)
 }
 }
 });
 }
 
 @Override
 protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
 switch (requestCode) {
 case TAKE_CAMERA:
 if (resultCode == RESULT_OK) {
 try {
 // 將拍攝的照片顯示出來(lái)
 Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
 imageView.setImageBitmap(bitmap);
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 }
 }
 break;
 case PICK_PHOTO:
 if (resultCode == RESULT_OK) { // 判斷手機(jī)系統(tǒng)版本號(hào)
 if (Build.VERSION.SDK_INT >= 19) {
 // 4.4及以上系統(tǒng)使用這個(gè)方法處理圖片
 handleImageOnKitKat(data);
 } else {
 // 4.4以下系統(tǒng)使用這個(gè)方法處理圖片
 handleImageBeforeKitKat(data);
 }
 }
 
 break;
 default:
 break;
 }
 }
 
 @TargetApi(19)
 private void handleImageOnKitKat(Intent data) {
 String imagePath = null;
 Uri uri = data.getData();
 if (DocumentsContract.isDocumentUri(this, uri)) {
 // 如果是document類(lèi)型的Uri,則通過(guò)document id處理
 String docId = DocumentsContract.getDocumentId(uri);
 if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
 String id = docId.split(":")[1];
 // 解析出數(shù)字格式的id
 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())) {
 // 如果是content類(lèi)型的Uri,則使用普通方式處理
 imagePath = getImagePath(uri, null);
 } else if ("file".equalsIgnoreCase(uri.getScheme())) {
 // 如果是file類(lèi)型的Uri,直接獲取圖片路徑即可
 imagePath = uri.getPath();
 }
 // 根據(jù)圖片路徑顯示圖片
 displayImage(imagePath);
 }
 
 /**
 * android 4.4以前的處理方式
 * @param data
 */
 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;
 // 通過(guò)Uri和selection來(lái)獲取真實(shí)的圖片路徑
 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);
 imageView.setImageBitmap(bitmap);
 } else {
 Toast.makeText(this, "獲取圖片失敗", Toast.LENGTH_SHORT).show();
 }
 }
 
}

那么以上的分析和代碼都講解了怎么解決“android怎么進(jìn)行拍照和取出相冊(cè)圖片?”這個(gè)問(wèn)題,如果你有不懂的方面也可以在W3Cschool搜索android就會(huì)出現(xiàn)很多相關(guān)的知識(shí)和課程可以讓大家學(xué)習(xí)。


0 人點(diǎn)贊