如何保存图片并在 PC 上访问它?

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

我正在关注 Google Camera Tutorial 申请 Android。此时此刻,我可以拍照、保存、显示路径并将位图显示到 ImageView 中。

下面是一个例子logcat当我要求我刚拍的照片的绝对路径时:

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

现在,我想通过 USB 将其传输到 PC 上。当我浏览到设备存储时,我可以看到我之前在代码中使用变量 Environment.DIRECTORY_PICTURES 调用的 public 文件夹 Picture。但是,此文件夹中没有任何内容。

Screenshot of my device's folders

无法在我的设备中插入 SD 卡进行测试。还有,我不想把图片放到缓存目录里,防止被删除。

这是我在清单中的权限:

<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" />

当用户点击相机按钮时:

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);
        }
    }
}

这是创建文件的方法

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;
}

我想我对 External Storage 有一些误解。 谁能解释一下为什么我不能保存图片并在 PC 上访问它?谢谢!

-- 编辑--

阅读下面的答案后,我尝试获取 OnActivityResult 中的文件并使用 Java IO 保存它。不幸的是,我用资源管理器查看时,图片文件夹中没有文件。

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();


    }

您当前将文件保存为临时文件,因此它不会在应用程序生命周期后保留在磁盘上。使用类似:

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

然后创建一个FileOutputStream写入它。

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

为了解决我的问题,我必须将文件写入应用程序的数据文件夹并使用 MediaScannerConnection。我放了一个 .txt 文件用于测试,但在它工作后你可以放任何其他文件。

我会把解决方案分享给有类似问题的人:

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.");
    }