简体   繁体   中英

How to save a picture and access it on a PC?

I'm following the Google Camera Tutorial for an Android application. At this moment, I'm able to take a picture, save it, show the path and show the bitmap into an ImageView.

Here is an exemple of the logcat when I ask for the absolute path of a picture I just took :

D/PATH:: /storage/emulated/0/Pictures/JPEG_20160210_140144_217642556.jpg

Now, I would like to transfer it on a PC via USB. When I broswe into the device storage, I can see the public folder Picture that I called earlier in my code with the variable Environment.DIRECTORY_PICTURES . However, there is nothing in this folder.

Screenshot of my device's folders

I can't insert a SD Card in my device to test. Also, I don't want to put the pictures into cache directory for preventing to be deleted.

Here is my permissions in Manifest :

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

When the user click on the camera buttons :

dispatchTakePictureIntent();
[...]
private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

This is method creating the file

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    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.d("PATH:", image.getAbsolutePath());
    return image;
}

I guess I misunderstood something about the External Storage . Can someone explain me why I can't save a picture and access it on a PC ? Thank you !

-- EDIT --

After reading an answer below, I tried to get the file in OnActivityResult and to save it with Java IO. Unfortunately, there is no file in Pictures folder when I look with Explorer.

if (requestCode == REQUEST_TAKE_PHOTO) {
        Log.d("AFTER", absolutePath);

       // Bitmap bitmap = BitmapFactory.decodeFile(absolutePath);
       // imageTest.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 2100, 3100, false));

        moveFile(absolutePath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());
    }

private void moveFile(String inputFile, String outputPath) {

    InputStream in = null;
    OutputStream out = null;
    try {

        //create output directory if it doesn't exist
        File dir = new File (outputPath);
        if (!dir.exists())
        {
            dir.mkdirs();
        }


        in = new FileInputStream(inputFile);
        out = new FileOutputStream(outputPath + imageFileName + ".jpg");

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;

        // write the output file
        out.flush();
        out.close();
        out = null;

        // delete the original file
        new File(inputFile).delete();


    }

You're currently saving the file as a temporary file, so it won't persist on disk after the application lifecycle. Use something like:

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File f = new File(Environment.getExternalStorageDirectory() + [filename])

And then create a FileOutputStream to write to it.

FileOutStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());

To solve my problem, I had to write the file into the application's data folder and to user the MediaScannerConnection . I've put a .txt file for testing, but after it works you can put any other file.

I'll share the solution for those who have a similar problem :

try
    {
        // Creates a trace file in the primary external storage space of the
        // current application.
        // If the file does not exists, it is created.
        File traceFile = new File(((Context)this).getExternalFilesDir(null), "TraceFile.txt");
        if (!traceFile.exists())
            traceFile.createNewFile();
        // Adds a line to the trace file
        BufferedWriter writer = new BufferedWriter(new FileWriter(traceFile, true /*append*/));
        writer.write("This is a test trace file.");
        writer.close();
        // Refresh the data so it can seen when the device is plugged in a
        // computer. You may have to unplug and replug the device to see the
        // latest changes. This is not necessary if the user should not modify
        // the files.
        MediaScannerConnection.scanFile((Context)(this),
                new String[] { traceFile.toString() },
                null,
                null);

    }
    catch (IOException e)
    {
        Log.d("FileTest", "Unable to write to the TraceFile.txt file.");
    }

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