我想在SD卡上的文件夹中保存多个图像,但在保存新图像时,之前的图像会被覆盖。如何在我的文件夹中保存多个图像?
File mydirectory = new File(Environment.getExternalStorageDirectory() + "/AppFolder");
if(!mydirectory.exists()){
mydirectory.mkdir();
}
if(mydirectory.exists()){
try {
File root = new File(Environment.getExternalStorageDirectory() +"/AppFolder");
File sdImageMainDirectory = new File(root , "pic.png");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
startCameraActivity();
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error occured. Please try again later.",Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void startCameraActivity() {
// TODO Auto-generated method stub
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, 101);
}
答案 0 :(得分:1)
您正在保存名称为pic.png
的每个文件。
您每次都需要更改文件名。
除了@David Xu的回答,如果你想每次都有唯一的名字,你可以在文件名的末尾附加一个unix时间戳,如下所示
dImageMainDirectory = new File(root, "pic_" + (System.currentTimeMillis() / 1000L) + ".png");
答案 1 :(得分:1)
变化
File sdImageMainDirectory = new File(root , "pic.png");
到
File sdImageMainDirectory = null;
int i = 0;
do {
sdImageMainDirectory = new File(root, "pic-" + i + ".png");
i++;
} while (sdImageMainDirectory.exists());
答案 2 :(得分:0)
您为每张照片使用相同的名称,这就是它被覆盖的原因
File sdImageMainDirectory = new File(root , "pic.png");
你将它们全部命名为pic.png
尝试开发像pic1.png,pic2.png这样的命名约定,或者你可以将png保存为当前时间戳的名称,如下所示:
//get timestamp into string
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
String timeStamp = df.format(today);
File sdImageMainDirectory = new File(root , timeStamp + ".png");
答案 3 :(得分:0)
您创建的每个文件都具有相同的名称。这是一个快速而肮脏的解决方案:
try{
File root = new File(Environment.getExternalStorageDirectory() +"/AppFolder");
int i = 0;
File sdImageMainDirectory = new File(root , "pic.png");
while(sdImageMainDirectory.exists()){
i++
sdImageMainDirectory = new File(root , "pic" +i+ ".png");
}
outputFileUri = Uri.fromFile(sdImageMainDirectory);
startCameraActivity();
} catch (Exception e) {