从存储中获取图像在 Android 中不起作用

Get image from storage not working in Android

我正在捕获图像并将其存储在移动设备的存储器中,但是当我获取此图像时,它无法在图像视图中显示任何内容。我已经尝试了很多代码来从文件中获取图像,但是 none 它们在我的模拟器或真正的三星设备中工作。

enter code here

 imageHolder = (ImageView)findViewById(R.id.captured_photo);
    Button capturedImageButton = (Button)findViewById(R.id.photo_button);
    capturedImageButton.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(photoCaptureIntent, requestCode);
        }
    });

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(this.requestCode == requestCode && resultCode == RESULT_OK){
        Bitmap bitmap = (Bitmap)data.getExtras().get("data");

        String partFilename = currentDateFormat();
        storeCameraPhotoInSDCard(bitmap, partFilename);


        // display the image from SD Card to ImageView Control
        String storeFilename = "photo_" + partFilename + ".jpg";
        Bitmap mBitmap = getImageFileFromSDCard(storeFilename);
        imageHolder.setImageBitmap(mBitmap);

    }
}

  private String currentDateFormat(){
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
    String  currentTimeStamp = dateFormat.format(new Date());
    return currentTimeStamp;
}

private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
    File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
    try {
        FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private Bitmap getImageFileFromSDCard(String filename){
  /*  Bitmap bitmap = null;
    File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
    try {
        FileInputStream fis = new FileInputStream(imageFile);
        bitmap = BitmapFactory.decodeStream(fis);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return bitmap; */

    File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
   // File imgFile = new  File(filename);
            //("/sdcard/Images/test_image.jpg");
    Bitmap myBitmap;

    if(imageFile.exists()){

         myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());

       // ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

      //  myImage.setImageBitmap(myBitmap);

        return myBitmap;

    }
    return null;
}

首先确保您已经在 "AndroidManifest" 中声明了 "Access External Storage" 和 "Access Hardware Camera" 权限,如果您使用的是 Android 版本 23 或 23+,那么您有在 运行 时间获得权限。 如果这不是问题,请使用下面给出的代码,它对我来说工作正常。

对于相机:

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(takePicture, ACTION_REQUEST_CAMERA);

画廊:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

            Intent chooser = Intent.createChooser(intent, "Choose a Picture");
            startActivityForResult(chooser, ACTION_REQUEST_GALLERY);

OnActivityResultMethod:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK)    {

        switch (requestCode) {
            case ACTION_REQUEST_GALLERY:
                Uri galleryImageUri = data.getData();
                try{
                    Log.e("Image Path Gallery" , getPath(getActivity() , galleryImageUri));
                    selectedImagePath = getPath(getActivity() , galleryImageUri);
                } catch (Exception ex){
                    ex.printStackTrace();
                    Log.e("Image Path Gallery" , galleryImageUri.getPath());
                    selectedImagePath = galleryImageUri.getPath();
                }

                break;

            case ACTION_REQUEST_CAMERA:
                // Uri cameraImageUri = initialURI;
                Uri cameraImageUri = data.getData();
                Log.e("Image Path Camera" , getPath(cameraImageUri));
                selectedImagePath = getPath(cameraImageUri);
                break;
        }

    }
}

获取相机返回图像路径的方法:

/**
 * helper to retrieve the path of an image URI
 */
public String getPath(Uri uri) {
    // just some safety built in
    if( uri == null ) {
        // TODO perform some logging or show user feedback
        return null;
    }
    // try to retrieve the image from the media store first
    // this will only work for images selected from gallery
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
    if( cursor != null ){
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    // this is our fallback here
    return uri.getPath();
}