从相册选取照片

明确:
Android 从4.4(API19)版本开始选取相册中的图片不再时返回真实图片的Uri,而是封装过的Uri,因此如果是4.4版本以上的手机需要对这个uri进行解析。4.4以下的版本不需要,因为返回的是真实的uri
判断Uri是document类型的话,需要取出docume id进行处理 ,如果是media类型的话还需要进一步解析

package com.example.choosepictest;

import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    public static  final  int TAKE_PHOTO = 1;

    public  static final int CROP_PHOTO = 2 ;

    public  static  final  int CHOOSE_PHOTO = 3;

    private Button chooseFromAlbum ;

    private Button takephoto;

    private ImageView picture ;

    private Uri imageUri ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        takephoto = (Button) findViewById(R.id.take_phone);
        picture = (ImageView) findViewById( R.id.picture) ;
        chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);
        takephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建File对象,用于存储拍照后的照片
                File outputImage = new File(Environment.getExternalStorageDirectory(),"output_image.jpg");
                System.out.println(Environment.getExternalStorageDirectory());
                try {
                    if(outputImage.exists()){
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                }catch (IOException e){
                    e.printStackTrace();
                }
                imageUri = Uri.fromFile(outputImage);
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                startActivityForResult(intent , TAKE_PHOTO);//需要返回结果判断拍照成功的故用这个方法
            }
        });


        chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("android.intent.action.GET_CONTENT");
                intent.setType("image/*");
                startActivityForResult(intent , CHOOSE_PHOTO);
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case TAKE_PHOTO:
                if(resultCode == RESULT_OK){
                    Intent intent = new Intent("com.android.camera.action.CROP");//为系统剪裁的Action

                    intent.setDataAndType(imageUri ,"image/*"); //设置剪裁的属性类型
                    intent.putExtra("scale",true);//scale为缩放的意思

                    intent.putExtra(MediaStore.EXTRA_OUTPUT , imageUri);
                    startActivityForResult(intent , CROP_PHOTO); //需要返回结果来判断是否截图成功的故用这个方法

                }
                break;
            case CROP_PHOTO:
                if(resultCode==RESULT_OK){
                    try{

                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));//而contentresolver则是用于管理所有程序的contentprovider实例
                        picture.setImageBitmap(bitmap);
                    }catch (FileNotFoundException e){
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if(resultCode == RESULT_OK){
                    if(Build.VERSION.SDK_INT>=19){
                        //4.4及以上系统使用
                        handleImageOnKitKat(data);
                    }else{
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:break;
        }
    }

    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.document".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())){
//            //如果不是document类型的Uri,则用普通方式处理
//            imagePath = getImagePath(uri , null);
//
//        }
//
//        disPlayImage(imagePath);
    }

    private void handleImageBeforeKitKat(Intent data){
        Uri uri = data.getData() ;//获取图片真实的uri
      //  System.out.println(uri);
        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.moveToNext()){
                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();
        }
    }
}

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
   >
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Take photo"
    android:id="@+id/take_phone"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/choose_from_album"
        android:text="Choose From Album" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/picture"
        android:layout_gravity="center_vertical"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.choosepictest">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>
    </application>

</manifest>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值