在生活不斷的富裕中我們對于身邊的事情都喜歡用手機拍照記錄自己的每個時刻,那么今天我們就來講下有關(guān)于“android怎么進行拍照和取出相冊圖片?”這個問題的解決方法和相關(guān)內(nèi)容分享!
獲取圖片方式: (類似更換頭像的效果)
1、手機拍照 選擇圖片;
2、相冊選取圖片;
本文只是簡單實現(xiàn)該功能,頁面展示有些簡陋,運行效果圖如下:
創(chuàng)建xml布局文件(activity_main.xml ): 頭部兩個Button按鈕,一個控制從相冊選擇照片,一個控制啟動相冊拍照選擇圖片。底部為一個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="相冊選取"
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)之前, 訪問SD卡的應(yīng)用關(guān)聯(lián)目錄需要聲明權(quán)限的,從4.4系統(tǒng)開始不再需要權(quán)限聲明。相關(guān)權(quán)限變成動態(tài)申請。
第一部分:拍照獲取圖片
我們將拍照的圖片放在SD卡關(guān)聯(lián)緩存目錄下。調(diào)用getExternalCacheDir()方法得到關(guān)聯(lián)緩存目錄, 具體的路徑是/sdcard/Android/data/<package name>/cache。 那么為什么要使用應(yīng)用關(guān)聯(lián)緩目錄來存放圖片呢?因為從Android 6.0系統(tǒng)開始, 讀寫SD卡被列為了危險權(quán)限, 如果將圖片存放在SD卡的任何其他目錄, 都要進行運行時權(quán)限處理, 使用應(yīng)用關(guān)聯(lián)
目錄則可以跳過這一步。
**
* 拍照 或 從相冊獲取圖片
*/
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);
//通過攝像頭拍照
btn_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 創(chuàng)建File對象,用于存儲拍照后的圖片
//存放在手機SD卡的應(yīng)用關(guān)聯(lián)緩存目錄下
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
/* 從Android 6.0系統(tǒng)開始,讀寫SD卡被列為了危險權(quán)限,如果將圖片存放在SD卡的任何其他目錄,
都要進行運行時權(quán)限處理才行,而使用應(yīng)用關(guān)聯(lián) 目錄則可以跳過這一步
*/
try {
if (outputImage.exists()) {
outputImage.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
/*
7.0系統(tǒng)開始,直接使用本地真實路徑的Uri被認為是不安全的,會拋 出一個FileUriExposedException異常。
而FileProvider則是一種特殊的內(nèi)容提供器,它使用了和內(nèi) 容提供器類似的機制來對數(shù)據(jù)進行保護,
可以選擇性地將封裝過的Uri共享給外部,從而提高了 應(yīng)用的安全性
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//大于等于版本24(7.0)的場合
imageUri = FileProvider.getUriForFile(MainActivity.this, "com.feige.pickphoto.fileprovider", outputImage);
} else {
//小于android 版本7.0(24)的場合
imageUri = Uri.fromFile(outputImage);
}
//啟動相機程序
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 {
// 將拍攝的照片顯示出來
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
}
從Android 7.0開始, 直接使用本地真實路徑的Uri被認為是不安全的, 會拋出一個FileUriExposedException異常。 FileProvider則是一種特殊的內(nèi)容提供器, 它使用了和內(nèi)容提供器類似的機制來對數(shù)據(jù)進行保護, 可以選擇性地將封裝過的Uri共享給外部, 從而提高了應(yīng)用的安全性。
首先要在AndroidManifest.xml中對內(nèi)容提供器進行注冊了:
<?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 就是用來指定Uri 共享的,
name 屬性的值可以隨便填, path 屬性的 值表示共享的具體路徑。
這里設(shè)置 . 就表示將整個SD卡進行共享 -->
<external-path
name="my_images"
path="." />
</paths>
第二部分:從相冊獲取圖片
/**
* 拍照 或 從相冊獲取圖片
*/
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);
//從相冊選擇圖片
choose_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//動態(tài)申請獲取訪問 讀寫磁盤的權(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 {
//打開相冊
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
intent.setType("image/*");
startActivityForResult(intent, PICK_PHOTO); // 打開相冊
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
switch (requestCode) {
case PICK_PHOTO:
if (resultCode == RESULT_OK) { // 判斷手機系統(tǒng)版本號
if (Build.VERSION.SDK_INT >= 19) {
// 4.4及以上系統(tǒng)使用這個方法處理圖片
handleImageOnKitKat(data);
} else {
// 4.4以下系統(tǒng)使用這個方法處理圖片
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類型的Uri,則通過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類型的Uri,則使用普通方式處理
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
// 如果是file類型的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;
// 通過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);
imageView.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "獲取相冊圖片失敗", 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;
/**
* 拍照 或 從相冊獲取圖片
*/
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);
//通過攝像頭拍照
btn_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 創(chuàng)建File對象,用于存儲拍照后的圖片
//存放在手機SD卡的應(yīng)用關(guān)聯(lián)緩存目錄下
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
/** 從Android 6.0系統(tǒng)開始,讀寫SD卡被列為了危險權(quán)限,如果將圖片存放在SD卡的任何其他目錄,
*都要進行運行時權(quán)限處理才行,而使用應(yīng)用關(guān)聯(lián) 目錄則可以跳過這一步
*/
try {
if (outputImage.exists()) {
outputImage.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
/**
*7.0系統(tǒng)開始,直接使用本地真實路徑的Uri被認為是不安全的,會拋 出一個FileUriExposedException異常。
*而FileProvider則是一種特殊的內(nèi)容提供器,它使用了和內(nèi) 容提供器類似的機制來對數(shù)據(jù)進行保護,
*可以選擇性地將封裝過的Uri共享給外部,從而提高了 應(yīng)用的安全性
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//大于等于版本24(7.0)的場合
imageUri = FileProvider.getUriForFile(MainActivity.this, "com.feige.pickphoto.fileprovider", outputImage);
} else {
//小于android 版本7.0(24)的場合
imageUri = Uri.fromFile(outputImage);
}
//啟動相機程序
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);
}
});
//從相冊選擇圖片
choose_photo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//動態(tài)申請獲取訪問 讀寫磁盤的權(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 {
//打開相冊
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT"
intent.setType("image/*");
startActivityForResult(intent, PICK_PHOTO); // 打開相冊
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
switch (requestCode) {
case TAKE_CAMERA:
if (resultCode == RESULT_OK) {
try {
// 將拍攝的照片顯示出來
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
case PICK_PHOTO:
if (resultCode == RESULT_OK) { // 判斷手機系統(tǒng)版本號
if (Build.VERSION.SDK_INT >= 19) {
// 4.4及以上系統(tǒng)使用這個方法處理圖片
handleImageOnKitKat(data);
} else {
// 4.4以下系統(tǒng)使用這個方法處理圖片
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類型的Uri,則通過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類型的Uri,則使用普通方式處理
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
// 如果是file類型的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;
// 通過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);
imageView.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "獲取圖片失敗", Toast.LENGTH_SHORT).show();
}
}
}
那么以上的分析和代碼都講解了怎么解決“android怎么進行拍照和取出相冊圖片?”這個問題,如果你有不懂的方面也可以在W3Cschool搜索android就會出現(xiàn)很多相關(guān)的知識和課程可以讓大家學(xué)習。