android 跳转相册选择图片并返回展示

2017-11-14  本文已影响0人  overhaha

1.点击事件跳转

private void selectImage() {
      Intent intent = new Intent();
      intent.setType("image/*");
      intent.setAction(Intent.ACTION_GET_CONTENT);
      startActivityForResult(Intent.createChooser(intent,"Browser Image..."),REQUEST_GET_IMAGE);
  }

2.获取返回的图片并设置到ImageView中

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ( resultCode == RESULT_OK && data != null){
            Uri uri = data.getData();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            try{
                InputStream inputStream = getContentResolver().openInputStream(uri);
                BitmapFactory.decodeStream(inputStream,null,options);
                inputStream.close();
                int height = options.outHeight;
                int width = options.outWidth;
                int sampleSize = 1;
                int max = Math.max(height,width);
                if (max>MAX_SIZE){
                    int nw = width/2;
                    int nh = height/2;
                    while ((nw/sampleSize)> MAX_SIZE || (nh / sampleSize)>MAX_SIZE){
                        sampleSize *=2;
                    }
                }
                options.inSampleSize = sampleSize;
                options.inJustDecodeBounds = false;
                selectdBitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri),null,options);
                imageView.setImageBitmap(selectdBitmap);
            }catch (IOException ioe){
                Log.i(TAG, ioe.getMessage());
            }

        }
    }

定义的几个常量

    private Bitmap selectdBitmap;
    private  int REQUEST_GET_IMAGE = 1;
    private  int MAX_SIZE = 769;
    private ImageView imageView;
上一篇 下一篇

猜你喜欢

热点阅读