覆盖sd卡android上的图像

时间:2013-06-07 11:02:41

标签: android

按钮点击后,我在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();
        }

1 个答案:

答案 0 :(得分:2)

什么是

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);

    }