使用Camera intent Android时未创建目录

时间:2013-01-11 08:57:12

标签: android

我试图保存相机意图拍摄的图像。我的代码没有工作,所以当我添加检查目录是否成立时,它应该是不是。什么可能是错的? 我试着在模拟器上。

01-11 13:50:28.946: D/file(1161):  file is /mnt/sdcard/M3
01-11 13:50:28.946: D/file(1161):  photo is /mnt/sdcard/M3/3_1.jpg

我在日志中得到了上述内容。

以下是我打开相机的按钮上的代码

File sdCard = Environment.getExternalStorageDirectory();
            File file = new File (sdCard.getAbsolutePath() , File.separator + "/M3");
            file.mkdirs();
            String name = e_id + "_" + (size+1)+ ".jpg";
            File newfile = new File(file,name);
            newfile.mkdir();

                Log.d("file"," file is " + file.toString());
                Log.d("file"," photo is " + newfile.toString());


            if(!file.mkdir())
            {
                Log.d("file"," not created ");
                }
            if(!newfile.mkdir())
            {
                Log.d("newfile"," not created ");
                }
            else
            {
                outputFileUri = Uri.fromFile(newfile);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                startActivityForResult(intent, TAKE_PICTURE);


            }

2 个答案:

答案 0 :(得分:1)

问题在于您将图像文件视为目录:

newfile.mkdir();

尝试:

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath(), File.separator + "/M3");
if (!dir.mkdirs())
{
    Log.e(TAG, "Failed to create directory " + dir);
    return false;    // Assuming this is in a method returning boolean
}
String filename = e_id + "_" + (size+1)+ ".jpg";
File file = new File(dir, filename);

Log.d(TAG, "dir is " + dir.toString());
Log.d(TAF, "file is " + file.toString());

outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);

注意:您需要更好地命名变量; file不是文件,而是目录。 newfile是您在此代码段中唯一关注的文件,因此请将其称为file

答案 1 :(得分:0)

替换此行

File file = new File (sdCard.getAbsolutePath() , File.separator + "/M3");

这个。

File file = new File (sdCard.getAbsolutePath()+"/YourDirectoryName");