我在单击按钮时成功地将图像保存在我的 SD 卡上。当我保存另一张照片时,我的应用程序崩溃了。我没有覆盖以前的图像,因为我希望图像名称保持不变。我该怎么做。
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte[] image=stream.toByteArray();
System.out.println("byte array:"+image);
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "myfile");
imagesFolder.mkdirs();
String fileName = "myfile.jpg";
File output = new File(imagesFolder, fileName);
while (output.exists()){
fileName = "myfile.jpg";
output = new File(imagesFolder, fileName);
}
while (output.exists()){
fileName = "myfile.jpg";
output = new File(imagesFolder, fileName);
}
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
//bitmap image here
imageFileOS.write(image);
imageFileOS.flush();
imageFileOS.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
最佳答案
什么是
while (output.exists()){
fileName = "myfile.jpg";
output = new File(imagesFolder, fileName);
}
这将无限循环您的代码。
改用
if (output.exists()){
output.delete(); //DELETE existing file
fileName = "myfile.jpg";
output = new File(imagesFolder, fileName);
}
关于android - 覆盖SD卡android上的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16982554/