9

我有一个程序可以通过 Intent 打开相机拍照。这么多部分已经很好了。但是,我希望它以某个文件名保存到某个文件夹(文件名是可选的,但它真的很有帮助)。

这就是我到目前为止所拥有的。

这是打开相机的代码行:

//TODO camera stuff.
Intent openCam = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

//The two lines of code below were commented out at first.
//They were eventually added when I tried to save it with a custom name and destination
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
openCam.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

startActivityForResult(openCam, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

结果处理程序在这里:

//TODO handle result
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
   if (resultCode == RESULT_OK) {
         // Image captured and saved to fileUri specified in the Intent
         Toast.makeText(this, "Image saved to:\n" +
                     data.getData(), Toast.LENGTH_LONG).show();
            System.out.println("I am here");

   } 
   else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
   } 
   else {
            // Image capture failed, advise user
   }
}

在我实现以下两种方法之前,代码运行良好。但是,它以默认文件名(时间戳版本)保存到默认文件夹。吐司显示“图像已保存到:null”,因为我还没有设置那部分。

所以这里是应该处理自定义文件名和目标的方法

/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
      return Uri.fromFile(getOutputMediaFile(type));
}

/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.

    Environment.getExternalStorageState();

    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
              Environment.DIRECTORY_PICTURES), "MyCameraApp");
    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE){
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
        "IMG_"+ timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}

*这些代码来自 developer.android.com 的相机指南。

上面的代码设法打开相机并拍照并保存它们。但是,当用户决定停止拍照并按返回键时,就会出现问题。发生的情况是应用程序强制关闭并给出此错误:

10-21 12:44:33.699: E/AndroidRuntime(13016): FATAL EXCEPTION: main
10-21 12:44:33.699: E/AndroidRuntime(13016): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {com.AIC.QRCodeScanner/com.AIC.QRCodeScanner.QRCodeScanner}: java.lang.NullPointerException
10-21 12:44:33.699: E/AndroidRuntime(13016): at android.app.ActivityThread.deliverResults(ActivityThread.java:2536)
10-21 12:44:33.699: E/AndroidRuntime(13016): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2578)
10-21 12:44:33.699: E/AndroidRuntime(13016): at android.app.ActivityThread.access$2000(ActivityThread.java:117)
10-21 12:44:33.699: E/AndroidRuntime(13016): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:965)
10-21 12:44:33.699: E/AndroidRuntime(13016): at android.os.Handler.dispatchMessage(Handler.java:99)
10-21 12:44:33.699: E/AndroidRuntime(13016): at android.os.Looper.loop(Looper.java:123)
10-21 12:44:33.699: E/AndroidRuntime(13016): at android.app.ActivityThread.main(ActivityThread.java:3691)
10-21 12:44:33.699: E/AndroidRuntime(13016): at java.lang.reflect.Method.invokeNative(Native Method)
10-21 12:44:33.699: E/AndroidRuntime(13016): at java.lang.reflect.Method.invoke(Method.java:507)
10-21 12:44:33.699: E/AndroidRuntime(13016): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
10-21 12:44:33.699: E/AndroidRuntime(13016): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
10-21 12:44:33.699: E/AndroidRuntime(13016): at dalvik.system.NativeStart.main(Native Method)
10-21 12:44:33.699: E/AndroidRuntime(13016): Caused by: java.lang.NullPointerException
10-21 12:44:33.699: E/AndroidRuntime(13016): at com.AIC.QRCodeScanner.QRCodeScanner.onActivityResult(QRCodeScanner.java:379)
10-21 12:44:33.699: E/AndroidRuntime(13016): at android.app.Activity.dispatchActivityResult(Activity.java:3934)
10-21 12:44:33.699: E/AndroidRuntime(13016): at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
10-21 12:44:33.699: E/AndroidRuntime(13016):    
... 11 more

它指向的线将是这条线(第 379 行):data.getData(), Toast.LENGTH_LONG

/Pictures/MyCameraApp但是,这些文件与拍摄的 Instagram 照片一起保存在该文件夹中。

所以问题是: 1.有没有办法让 onActivityResult 正常工作?我知道我可以诉诸使用 startActivity 以免杀死应用程序。2. 有没有办法只用相机拍一张?因此,在用户保存照片后,应用程序会返回到主要活动。3. 另外,我可以将它保存到我自己的文件夹中吗?我不确定它为什么将照片保存在 中/Pictures/MyCameraApp,我希望它只保存到/MyCameraApp.

我想我在这里错过了一些简单的东西。

4

3 回答 3

22

这是使它工作的代码:

//camera stuff
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

//folder stuff
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();

File image = new File(imagesFolder, "QR_" + timeStamp + ".png");
Uri uriSavedImage = Uri.fromFile(image);

imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

它打开相机并拍摄一张照片(在用户保存拍摄的图像后它会返回到主要活动。它将图像保存到指定的文件夹。

于 2012-10-25T13:43:32.967 回答
7

您可以在文件夹中获取照片,但为此您必须使用以下代码传递带有意图的文件名

Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File out = Environment.getExternalStorageDirectory();
out = new File(out, imagename);
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
startActivityForResult(i, CAMERA_RESULT);

out 文件包含完整路径和文件名。

现在处理 onActivityResult() 方法并检查结果的状态,如果结果为 RESULT_OK,然后使用您提供的文件名来访问照片。

您可以参考How to get camera result as a uri in data 文件夹?更多选择。

编辑

您将data.getData()变为 null,因为如果您通过意图传递文件 url,它将为 null。实际上,您已经有了与 Intent 一起传递的文件路径,那么为什么要尝试从包中获取它onActivityResult()呢?

于 2012-10-21T05:25:27.917 回答
0

这可能对你有帮助

File file=new File(Environment.getExternalStorageDirectory(),"file name");

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        opencam();
    }
});

protected void opencam() {
    Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);    
    in.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(file));
    startActivityForResult(in,1);
}
于 2016-02-14T16:00:43.457 回答