Android 从相册中选择照片

2021-09-24 15:07:41 浏览数 (1)

实际效果图:

代码实现:

  1. 权限配置
  2. 点击事件绑定
  3. 相册访问
  4. 根据路径设置图片
  5. 其他方法

权限

首先,现在 mainfest.xml 文件中添加以下权限:

代码语言:javascript复制
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

点击事件

点击跳转相册

代码语言:javascript复制
imageView01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                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);
                }
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, IMAGE_REQUEST_CODE);
            }
        });

不同手机返回图片uri不同,此处进行转换

可以不添加( 如果,不添加,则其他方法也没用 )

代码语言:javascript复制
    @TargetApi(19)
    private void handleImageOmKitKat(Intent data){
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this,uri)){
            //如果document类型是U日,则通过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())){
            //如果是普通类型 用普通方法处理
            imagePath = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            //如果file类型位uri直街获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
    }

关于方法:onActivityResult()

代码语言:javascript复制
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    //在相册里面选择好相片之后调回到现在的这个activity中
    switch (requestCode) {
        case IMAGE_REQUEST_CODE://这里的requestCode是我自己设置的,就是确定返回到那个Activity的标志
            if (resultCode == RESULT_OK) {//resultcode是setResult里面设置的code值
                try {
                    Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    path = cursor.getString(columnIndex);  //获取照片路径
                    cursor.close();

                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 1;
                    bitmap = BitmapFactory.decodeFile(path,options);
                    imageView01.setImageBitmap(bitmap);
                    chnage();
                    Toast.makeText(MainActivity.this,path,Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    // TODO Auto-generatedcatch block
                    e.printStackTrace();
                }
            }
            break;
    }
}

在这里通过放回路径设置头像,但由于图片路径生成可能有一定延时,所以这里开一个线程等待:

代码语言:javascript复制
/*定义一个Handler,定义延时执行的行为*/
public  void chnage(){
    new Thread(){
        @Override
        public void run() {
            while ( bitmap == null ){
                bitmap = BitmapFactory.decodeFile(path);
                Log.v("qwe","123");
            }
            Message message = handler.obtainMessage();
            message.obj = 0;
            handler.sendMessage(message);
        }
    }.start();
}

其他方法:

代码语言:javascript复制
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);
            imageView01.setImageBitmap(bitmap);
        }else {
            Toast.makeText(MainActivity.this,"fail to get image",Toast.LENGTH_SHORT).show();
        }
    }

相关变量:

代码语言:javascript复制
//从相册获得图片
Bitmap bitmap;
//判断返回到的Activity
private static final int IMAGE_REQUEST_CODE = 0;
//图片路径
private String path ;

private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        if((Integer)msg.obj==0){
            imageView01.setImageBitmap(bitmap);
        }
        super.handleMessage(msg);
    }
};

如有疑问欢迎在评论区指出,欢迎关注我获得更多资讯 ?

免费 Demo 地址:https://download.csdn.net/download/qq_43377749/10789981

0 人点赞