當(dāng)前位置:首頁(yè) > IT技術(shù) > 移動(dòng)平臺(tái) > 正文

android選擇圖片
2022-04-25 23:02:41

/**
 * 選擇圖片,2種實(shí)現(xiàn)方式
 */
  public void pickBackgroundPicture() {
      Logutil.e("pickBackgroundPicture");
      // 只顯示拍的照片和擴(kuò)展存儲(chǔ)根目錄下的圖片
      Intent intent = new Intent(Intent.ACTION_PICK,
              MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
      startActivityForResult(intent, REQUESTCODE_LOAD_IMAGE);

      // 可顯示全部圖片,但可能會(huì)彈出選擇瀏覽圖片的應(yīng)用選擇
/*Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, RESULTCODE_LOAD_IMAGE);
*/
  }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUESTCODE_LOAD_IMAGE:
                if (resultCode == RESULT_OK && null != data) {
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();

                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    Bitmap _Bitmap = null;
//          Bitmap _Bitmap = BitmapFactory.decodeFile(picturePath);
                    try {
                        _Bitmap = MyUtility.getBitmapByFile(new File(picturePath));
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                    if (_Bitmap == null) {
                        Log.d(TAG, "picturePath=" + picturePath);
                        break;
                    }
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                        mMainlayout.setBackground(new BitmapDrawable(getResources(),
                                _Bitmap));
                    } else {
                        mMainlayout.setBackgroundDrawable(new BitmapDrawable(
                                getResources(), _Bitmap));
                    }
//          setBackground(-1, _Bitmap, null, 2);
                    SharedPreferences.Editor _Editor = mSharedPreferences.edit();
                    _Editor.putString(KEY_SAVE_BACKGROUND, picturePath);
                    boolean _boolean = _Editor.commit();
                    if (false == _boolean) {
                        Log.d(TAG, "save background picture failed");
                    }
//                    cancelAlarm();
                }
                break;
        }
    }
?
轉(zhuǎn)自:https://www.jianshu.com/p/ef1749e3394c?

本文摘自 :https://www.cnblogs.com/

開通會(huì)員,享受整站包年服務(wù)立即開通 >