单击按钮从相册中选取图片并展示出来

在此基础代码上修改:调用摄像头拍照

1. 效果图




2. MainActivity.java

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.os.Bundle;import android.provider.DocumentsContract;import android.provider.MediaStore;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.util.Log;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;import java.io.File;import java.io.IOException;public class MainActivity extends AppCompatActivity {    public static final int TAKE_PHOTO = 1;    public static final int CHOOSE_PHOTO = 2;    private ImageView picture;    private Button takePhoto;    private Button chooseFromAlbum;    private Uri imageUri;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //获取控件实例        takePhoto = (Button) findViewById(R.id.take_photo);        chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);        picture = (ImageView) findViewById(R.id.picture);        //设置takePhoto按钮点击事件        takePhoto.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // 创建File对象,用于存储拍照后的图片                File outputImage = new File(getExternalCacheDir(), "output_image.jpg");                try {                    if (outputImage.exists()) {                        outputImage.delete();                    }                    outputImage.createNewFile();                } catch (IOException e) {                    e.printStackTrace();                }                if (Build.VERSION.SDK_INT < 24) {                    imageUri = Uri.fromFile(outputImage);                } else {                    imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cameraalbumtest.fileprovider", outputImage);                }                // 启动相机程序                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);                startActivityForResult(intent, TAKE_PHOTO);            }        });        //设置chooseFromAlbum按钮点击事件        chooseFromAlbum.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //处理运行时权限                //WRITE_EXTERNAL_STORAGE表示同时授予程序对SD卡读和写的能力                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission. WRITE_EXTERNAL_STORAGE }, 1);                } else {                    openAlbum();                }            }        });    }    private void openAlbum() {        Intent intent = new Intent("android.intent.action.GET_CONTENT");        intent.setType("image/*");        startActivityForResult(intent, CHOOSE_PHOTO); // 打开相册    }    @Override    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {        switch (requestCode) {            case 1:                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                    openAlbum();                } else {                    Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();                }                break;            default:        }    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        switch (requestCode) {            case TAKE_PHOTO:                if (resultCode == RESULT_OK) {                    try {                        // 将拍摄的照片显示出来                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));                        picture.setImageBitmap(bitmap);                    } catch (Exception e) {                        e.printStackTrace();                    }                }                break;            case CHOOSE_PHOTO:                if (resultCode == RESULT_OK) {                    // 判断手机系统版本号                    if (Build.VERSION.SDK_INT >= 19) {                        // 4.4及以上系统使用这个方法处理图片                        //4.4版本开始,选取相册中的图片不再返回图片真实的Uri了,而是一个封装过的Uri                        handleImageOnKitKat(data);                    } else {                        // 4.4以下系统使用这个方法处理图片                        handleImageBeforeKitKat(data);                    }                }                break;            default:                break;        }    }    @TargetApi(19)    private void handleImageOnKitKat(Intent data) {        String imagePath = null;        Uri uri = data.getData();        Log.d("TAG", "handleImageOnKitKat: uri is " + uri);        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]; // 解析出数字格式的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();        }        displayImage(imagePath); // 根据图片路径显示图片    }    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);            picture.setImageBitmap(bitmap);        } else {            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();        }    }}

3. activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.thinkpad.cameraalbumtest.MainActivity">        <Button        android:id="@+id/take_photo"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="点击拍照"/>        <Button        android:id="@+id/choose_from_album"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="从相册中选取照片"/>        <ImageView        android:id="@+id/picture"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"/>LinearLayout>

整理学习自郭霖大佬的《第一行代码》
目前小白一名,持续学习Android中,如有错误请批评指正!

更多相关文章

  1. android 指定组件的圆角图片处理
  2. android 图片放大缩小 多点缩放
  3. Android(安卓)软引用内存缓存图片
  4. Android(安卓)LayerDrawable
  5. android分辨率详解
  6. android 实现listView异步加载图片
  7. Android调用系统图库获取图片
  8. android2.3选择相册图片或者调用系统照相
  9. Android(安卓)中显示 Gif 格式图

随机推荐

  1. android:clearTaskOnLaunch的用法
  2. android 向服务端发送请求编码问题
  3. android 自动化压力测试-monkey 1 实践
  4. Android(安卓)View浜嬩欢鍒嗗彂鏈哄埗(婧
  5. 编译android vlc
  6. android ui线程和数据的分离
  7. Android 通知栏Notification的整合 全面
  8. android --天气预报
  9. Android官方MVP项目单元测试
  10. Android(安卓)自定义 View——手势密码