从相册选取图片

关键代码:

public class MainActivity extends Activity {

    public static final  int SELECT_PICTURE = 1;
    Bitmap bitmap = null;
    ImageView picture;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        picture = (ImageView)findViewById(R.id.picture);
    }

    protected void myClick(View v){
        if( v.getId() == R.id.choose_btn ){
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent,"选择图片"), SELECT_PICTURE );
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case SELECT_PICTURE:
                Uri uri = data.getData();
                ContentResolver cr = getContentResolver();
                try{
                    if (bitmap != null) {
                        bitmap.recycle();
                    }
            // 缩率图参数
                    BitmapFactory.Options opts=new BitmapFactory.Options();
                    opts.inSampleSize=2;
                    bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri),null,opts);
                }catch (FileNotFoundException e){
                    e.printStackTrace();
                }
                picture.setImageBitmap(bitmap);
                break;
        }
    }
}

权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

 

posted @ 2017-04-22 11:14  rorshach  阅读(309)  评论(0编辑  收藏  举报