獲取手機相簿圖片顯示並獲取路徑
阿新 • • 發佈:2019-01-25
- Intent intent = new Intent();
- intent.setAction(Intent.ACTION_PICK);
- intent.setType("image/*");
- startActivityForResult(intent, RESULT_LOAD_IMAGE);
- Uri uri = data.getData();
- String path = uri.getPath();
解決方案:在onActivityResult中,按照如下的方式,就可以在所有的手機上使用,不會出問題,親測:
- if (data != null) {
- Uri uri = data.getData();
- if (!TextUtils.isEmpty(uri.getAuthority())) {
- Cursor cursor = getContentResolver().query(uri,
-
new String[] { MediaStore.Images.Media.DATA },null, null
- if (null == cursor) {
- Toast.makeText(this, "圖片沒找到", Toast.LENGTH_SHORT).show();
- return;
- }
- cursor.moveToFirst();
- path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
-
cursor.close();
- } else {
- path = uri.getPath();
- }
- }else{
- Toast.makeText(this, "圖片沒找到", Toast.LENGTH_SHORT).show();
- return;
- }
/** * 開啟系統相簿,並選擇圖片 */
private int PHOTO_REQUEST_CUT = 22;public void selectPic(){ Intent intent = new Intent("android.intent.action.PICK");intent.setType("image/*");startActivityForResult(intent, 0);}
if(requestCode == 0){ if (data != null) { Uri uri = data.getData(); crop(uri); }else if(requestCode == PHOTO_REQUEST_CUT){ if (data != null) { Bitmap bitmap = data.getParcelableExtra("data"); back_image.setImageBitmap(bitmap); } }
private void crop(Uri uri) { // 裁剪圖片意圖 Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); // 裁剪框的比例,1:1 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // 裁剪後輸出圖片的尺寸大小 intent.putExtra("outputX", 250); intent.putExtra("outputY", 250); intent.putExtra("outputFormat", "JPEG");// 圖片格式 intent.putExtra("noFaceDetection", true);// 取消人臉識別 intent.putExtra("return-data", true); // 開啟一個帶有返回值的Activity,請求碼為PHOTO_REQUEST_CUT startActivityForResult(intent, PHOTO_REQUEST_CUT); }