简体   繁体   中英

Android - Unable to save images

I'm currently trying to get image saving to happen using the device built in camera. This is the code I'm using:

            PackageManager pm = getActivity().getPackageManager();
            if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                // * Ensure that there's a camera activity to handle the intent
                if (takePictureIntent.resolveActivity(pm) != null) {
                    // * Create the File where the photo should go
                    File photoFile = null;
                    try {
                        photoFile = ImageFileHelper.createImageFile();
                    } catch (IOException ex) {
                        // * Error occurred while creating the File
                        Timber.d("An error occurred while creating file: " + ex.getLocalizedMessage());
                    }
                    // * Continue only if the File was successfully created
                    if (photoFile != null) {
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                        startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PICTURE);
                    } else {
                        alertUserOfError(0);
                    }
                }
            } else {
                // * Inform user that they need a camera 
                // * to use this feature
                alertUserOfError(1);
            }

And here is the ImageFileHelper.createImageFile() function:

public static File createImageFile() throws IOException {

    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyy-MM-dd.ss", Locale.getDefault()).format(new Date());
    String imageFileName = "Original_Avatar_" + timeStamp;

    // * Create MyApp folder if not exist
    String path = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_PICTURES;
    File dir = new File(path + "/MyApp/Originals/");
    dir.mkdirs();

    File image = File.createTempFile(
        imageFileName,      /* prefix */
        ".png",             /* suffix */
        dir                 /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    filePath = "file:" + image.getAbsolutePath();
    Timber.d("image created at: " + filePath);
    return image;
}

My permissions & features:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>

This seems to work just fine on my test devices and the majority of my beta tester devices. However, there is one guy who reports that he gets an error message generated by alertUserOfError(0) (you'll see that in the above code), essentially that the photoFile is null.

He is using a rooted HTC One (M8) (htc_m8). Could this be an issue due to the device being rooted?

Any help is appreciated.

UPDATE 2015-05-30 I haven't had a chance to add reporting to the catch statement yet, but I did add a method to test for valid paths/directories. Here is how it works:

    StringBuilder build = new StringBuilder();

    String path_1 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "MyApp" + File.separator + "Cropped" + File.separator;
    File dir_1 = new File(path_1);

    dir_1.mkdirs();
    if (dir_1.exists()) {
        build.append("path 1 valid, ");
    } else {
        build.append("path 1 invalid, ");
    }

Using this same setup I also tested the following dirs:

Environment.getExternalStorageDirectory() + File.separator + "MyApp" + File.separator + "Cropped" + File.separator;
Environment.getDataDirectory() + File.separator + "MyApp" + File.separator + "Cropped" + File.separator;

The StringBuilder.toString() is then used as the message in an alert for the tester to send the results back to us.

The above resulted in all paths being invalid: path_1 invalid, path_2 invalid, path_3 invalid

So does this mean that those directories just don't exist on the HTC One (M8) (htc_m8) and cannot be created?

I had a similar situation. You are implementing the example given in the official docs. There is a problem implementing that example in some devices. This is how I solved it.

Replace:

Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES)

With:

private File createImageFile() throws IOException {
        // Create an image file name

Finally, make sure you call:

mkdirs() // and not mkdir()

Here's the code that should work for you:

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = new File(Environment.getExternalStorageDirectory().toString(), "whatever_directory_existing_or_not/sub_dir_if_needed/");
        storageDir.mkdirs(); // make sure you call mkdirs() and not mkdir()
        File image = File.createTempFile(
                imageFileName,  // prefix
                ".jpg",         // suffix
                storageDir      // directory
        );

        // Save a file: path for use with ACTION_VIEW intents

        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        Log.e("our file", image.toString());
        return image;
    }

I had a bad experience following the example given in Android Studio Documentation and I found out that there are many others experiencing the same about this particular topic here in stackoverflow, that is because even if we set

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

the problem persists in some devices.

My experience was that the example worked when I tried it in debug mode, after that 3 more tests passed, it so happened that my SD was suddenly corrupted, but I don't think it had to do with their example (funny). I bought a new SD card and tried it again (because I could not reformat my sd, however I tried), only to realize that still both release and debug mode did the same error log: directory does not exist ENOENT. Finally, I had to create the directories myself whick will contain the captured pictures from my phone's camera. And I was right, it works just perfect.

I hope this will help the ones out there searching for answers, because obviously, considering the age of your enquiry, you must have already solved this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM