简体   繁体   English

覆盖sd卡android上的图像

[英]Overwrite image on sd card android

I saved an image successfully on my sd card on button click. 按钮点击后,我在SD卡上成功保存了图像。 when i saved another picture my application crashed. 当我保存另一张照片时,我的应用程序崩溃了。 I have t overwrite the previous image as i want the image name to stays the same. 我没有覆盖以前的图像,因为我希望图像名称保持不变。 how can i do this. 我怎样才能做到这一点。

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

What is 什么是

while (output.exists()){
        fileName = "myfile.jpg";
        output = new File(imagesFolder, fileName);

    }

this will loop your code for unfinite. 这将使您的代码无限期循环。

Use instead 请改用

if (output.exists()){
output.delete(); //DELETE existing file
        fileName = "myfile.jpg";
        output = new File(imagesFolder, fileName);

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM