android實(shí)現(xiàn)拍照或從相冊(cè)選取圖片
從相冊(cè)或拍照更換圖片功能的實(shí)現(xiàn):(取圖無裁剪功能)
獲取圖片方式: (類似更換頭像的效果)
1、手機(jī)拍照 選擇圖片;
2、相冊(cè)選取圖片;
本文只是簡單實(shí)現(xiàn)該功能,頁面展示有些簡陋,運(yùn)行效果圖如下:

創(chuàng)建xml布局文件(activity_main.xml ): 頭部兩個(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)之前, 訪問SD卡的應(yīng)用關(guān)聯(lián)目錄需要聲明權(quán)限的,從4.4系統(tǒng)開始不再需要權(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)緩目錄來存放圖片呢?因?yàn)閺腁ndroid 6.0系統(tǒng)開始, 讀寫SD卡被列為了危險(xiǎn)權(quán)限, 如果將圖片存放在SD卡的任何其他目錄, 都要進(jìn)行運(yùn)行時(shí)權(quán)限處理, 使用應(yīng)用關(guān)聯(lián)
目錄則可以跳過這一步。
**
* 拍照 或 從相冊(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);
//通過攝像頭拍照
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)開始,讀寫SD卡被列為了危險(xiǎn)權(quán)限,如果將圖片存放在SD卡的任何其他目錄,
都要進(jìn)行運(yùn)行時(shí)權(quán)限處理才行,而使用應(yīng)用關(guān)聯(lián) 目錄則可以跳過這一步
*/
try {
if (outputImage.exists()) {
outputImage.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
/*
7.0系統(tǒng)開始,直接使用本地真實(shí)路徑的Uri被認(rèn)為是不安全的,會(huì)拋 出一個(gè)FileUriExposedException異常。
而FileProvider則是一種特殊的內(nèi)容提供器,它使用了和內(nèi) 容提供器類似的機(jī)制來對(duì)數(shù)據(jù)進(jìn)行保護(hù),
可以選擇性地將封裝過的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);
}
//啟動(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 {
// 將拍攝的照片顯示出來
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
}
從Android 7.0開始, 直接使用本地真實(shí)路徑的Uri被認(rèn)為是不安全的, 會(huì)拋出一個(gè)FileUriExposedException異常。 FileProvider則是一種特殊的內(nèi)容提供器, 它使用了和內(nèi)容提供器類似的機(jī)制來對(duì)數(shù)據(jù)進(jìn)行保護(hù), 可以選擇性地將封裝過的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 就是用來指定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)獲取訪問 讀寫磁盤的權(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 {
//打開相冊(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); // 打開相冊(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類型的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來獲取真實(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);
//通過攝像頭拍照
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)開始,讀寫SD卡被列為了危險(xiǎn)權(quán)限,如果將圖片存放在SD卡的任何其他目錄,
*都要進(jìn)行運(yùn)行時(shí)權(quán)限處理才行,而使用應(yīng)用關(guān)聯(lián) 目錄則可以跳過這一步
*/
try {
if (outputImage.exists()) {
outputImage.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
/**
*7.0系統(tǒng)開始,直接使用本地真實(shí)路徑的Uri被認(rèn)為是不安全的,會(huì)拋 出一個(gè)FileUriExposedException異常。
*而FileProvider則是一種特殊的內(nèi)容提供器,它使用了和內(nèi) 容提供器類似的機(jī)制來對(duì)數(shù)據(jù)進(jìn)行保護(hù),
*可以選擇性地將封裝過的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);
}
//啟動(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)獲取訪問 讀寫磁盤的權(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 {
//打開相冊(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); // 打開相冊(cè)
}
}
});
}
@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) { // 判斷手機(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類型的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來獲取真實(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();
}
}
}
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android實(shí)現(xiàn)拍照、選擇圖片并裁剪圖片功能
- Android啟動(dòng)相機(jī)拍照并返回圖片
- Android拍照保存在系統(tǒng)相冊(cè)不顯示的問題解決方法
- Android仿微信發(fā)表說說實(shí)現(xiàn)拍照、多圖上傳功能
- Android實(shí)現(xiàn)調(diào)用攝像頭進(jìn)行拍照功能
- android 拍照和上傳的實(shí)現(xiàn)代碼
- Android7.0實(shí)現(xiàn)拍照和相冊(cè)選取圖片功能
- Android開發(fā)從相冊(cè)中選取照片的示例代碼
- Android通過手機(jī)拍照或從本地相冊(cè)選取圖片設(shè)置頭像
相關(guān)文章
Android開發(fā)者常見的UI組件總結(jié)大全
Android開發(fā)中UI組件是構(gòu)建用戶界面的基本元素,下面這篇文章主要給大家介紹了關(guān)于Android開發(fā)者常見的UI組件總結(jié)的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-04-04
Android移動(dòng)開發(fā)recycleView的頁面點(diǎn)擊跳轉(zhuǎn)設(shè)計(jì)實(shí)現(xiàn)
這篇文章主要介紹了Android移動(dòng)開發(fā)recycleView的頁面點(diǎn)擊跳轉(zhuǎn)設(shè)計(jì)實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Android仿淘寶view滑動(dòng)至屏幕頂部會(huì)一直停留在頂部的位置
這篇文章主要介紹了Android仿淘寶view滑動(dòng)至屏幕頂部會(huì)一直停留在頂部的位置的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-11-11
Android字符串和十六進(jìn)制相互轉(zhuǎn)化出現(xiàn)的中文亂碼問題
這篇文章主要介紹了Android字符串和十六進(jìn)制相互轉(zhuǎn)化出現(xiàn)的中文亂碼問題的相關(guān)資料,需要的朋友可以參考下2016-02-02
Android編程使用android-support-design實(shí)現(xiàn)MD風(fēng)格對(duì)話框功能示例
這篇文章主要介紹了Android編程使用android-support-design實(shí)現(xiàn)MD風(fēng)格對(duì)話框功能,涉及Android對(duì)話框、視圖、布局相關(guān)操作技巧,需要的朋友可以參考下2017-01-01
Android編程實(shí)現(xiàn)ListView內(nèi)容無限循環(huán)顯示的方法
這篇文章主要介紹了Android編程實(shí)現(xiàn)ListView內(nèi)容無限循環(huán)顯示的方法,通過繼承Adapter類實(shí)現(xiàn)ListView中的數(shù)據(jù)無限循環(huán)顯示功能,需要的朋友可以參考下2017-06-06

