相机没有在SD卡上保存图像(有时工作)

时间:2013-12-15 05:44:25

标签: android camera android-camera android-camera-intent

我想在我的应用程序中调用相机拍照并将其保存在SD卡中...

我的代码有时会工作而有时不工作.. 我不明白为什么?这是我的代码

public class MainActivity extends Activity {

int TAKE_PHOTO_CODE = 0;
public static int count = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final String dir = Environment.getExternalStorageDirectory().getPath() + "/picFolder/"; 
    File newdir = new File(dir); 
    newdir.mkdirs();

Button capture = (Button) findViewById(R.id.button1);
capture.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

        count++;
        String file = dir+count+".jpg";
        File newfile = new File(file);

        try {
            newfile.createNewFile();
        } catch (IOException e) {}       

        Uri outputFileUri = Uri.fromFile(newfile);

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

        startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);

    }
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
    Log.d("CameraDemo", "Pic saved");
    }

 }

}

我尝试了很多东西,但没有做对。

1 个答案:

答案 0 :(得分:1)

使用帮助方法: 在主活动类中添加以下方法。这些方法有助于从SD卡创建和获取文件。

/**
 * Creating file uri to store image/video
 */
public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/*
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                    + IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

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

    return mediaFile;
}