1.声明相关权限
<uses-permission android:name="android.permission.READ_PHONE_STATE" /><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
2.设置路径
<providerandroid:authorities="com.example.cameraalbumtest.fileprovider"android:name="android.support.v4.content.FileProvider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths"/></provider>
**
3.在res目录下创建xml文件夹,在该文件夹下创建file_paths.xml文件
**
<?xml version="1.0" encoding="utf-8"?><paths xmlns:android="/apk/res/android"><external-pathname="img"path=""></external-path></paths>
4.布局文件,一个imageView显示图片,两个按钮,一个按钮用来拍照,一个按钮从相册中选取图片。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><ImageViewandroid:layout_width="200dp"android:layout_height="200dp"android:id="@+id/img"android:layout_gravity="center"android:layout_marginTop="30sp"/><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="20dp"android:layout_marginLeft="50dp"android:layout_marginRight="50dp"android:textColor="#000"android:id="@+id/btn"android:text="开始拍照"/><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="20dp"android:layout_marginLeft="50dp"android:layout_marginRight="50dp"android:textColor="#000"android:id="@+id/btn2"android:text="从相册中选择"/></LinearLayout>
**
- 5.MainActivity.java 主程序代码
**
package .activity_demo;import android.Manifest;import android.content.ContentUris;import android.content.Context;import android.content.Intent;import android.content.pm.PackageManager;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import .Uri;import android.os.Build;import android.provider.DocumentsContract;import android.provider.MediaStore;import android.support.annotation.NonNull;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;import java.io.IOException;public class CapActivity extends AppCompatActivity {Context context;ImageView imageView;Button btn; //拍照按钮Button btn2; //从相册中选择Uri uri; //显示拍的图片@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_xiang_ji);context = CapActivity.this;//获取控件实例imageView = findViewById(R.id.img);btn = findViewById(R.id.btn);btn2 = findViewById(R.id.btn2);//点击拍照btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//创建一个文件存放SD卡的应用关联缓存目录File file = new File(getExternalCacheDir(), "test.jpg");try {if (file.exists()) {file.delete();}file.createNewFile();} catch (IOException e) {e.printStackTrace();}//判断安卓系统版本if (Build.VERSION.SDK_INT >= 24) {//将File对象转换成一个封装过的Uri对象,接收3个参数,第一个是上下文,第二个是任意唯一字符串,第三个File对象uri = FileProvider.getUriForFile(context, "com.example.cameraalbumtest.fileprovider", file);} else {uri = Uri.fromFile(file);}//启动相机Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");//指定图片的输出地址intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);startActivityForResult(intent, 1);}});//从相册中选择图片btn2.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (ContextCompat.checkSelfPermission(context,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(CapActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);} else {openAlbum();}}});}/*** 打开相册*/private void openAlbum() {Intent intent = new Intent("android.intent.action.GET_CONTENT");intent.setType("image/*");startActivityForResult(intent, 3);}private void handeImage(Intent data) {String imagePath = null;Uri uri2 = data.getData();if (DocumentsContract.isDocumentUri(this, uri2)) {String docid = DocumentsContract.getDocumentId(uri2);if ("com.android.providers.media.documents".equals(uri2.getAuthority())) {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(uri2.getAuthority())) {Uri contenUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docid));imagePath = getImagePath(contenUri, null);}} else if ("content".equalsIgnoreCase(uri2.getScheme())) {imagePath = getImagePath(uri2, null);} else if ("file".equalsIgnoreCase(uri2.getScheme())) {imagePath = uri2.getPath();}displayIaage(imagePath);}private void handleImageBefor(Intent data) {Uri uri = data.getData();String imagePath = getImagePath(uri, null);displayIaage(imagePath);}private String getImagePath(Uri uri, String selection) {String path = null;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 displayIaage(String path) {if (path != null) {Bitmap bitmap = BitmapFactory.decodeFile(path);imageView.setImageBitmap(bitmap);} else {Toast.makeText(context, "failed to get image", Toast.LENGTH_SHORT).show();}}/*** 手机权限结果回调** @param requestCode* @param permissions* @param grantResults*/@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {if (requestCode == 2) {if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {openAlbum();} else {Toast.makeText(context, "You denied the permission", Toast.LENGTH_SHORT).show();}}}/*** 如果拍照成功,则回调该方法得到所拍照的图片** @param requestCode 请求码* @param resultCode 响应码* @param data 所得到的图片数据*/@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {switch (requestCode) {case 1:if (resultCode == RESULT_OK) {try {Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));imageView.setImageBitmap(bitmap);} catch (FileNotFoundException e) {e.printStackTrace();}}break;case 3:if (resultCode == RESULT_OK) {if (Build.VERSION.SDK_INT >= 19) {handeImage(data);} else {handleImageBefor(data);}}break;}}}
如果觉得《Android 调用手机摄像头拍照显示图片和从相册中导入图片并显示》对你有帮助,请点赞、收藏,并留下你的观点哦!