android - 覆盖SD卡android上的图像

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

最佳答案

什么是

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/

相关文章:

android - cordova 构建 android 在 :app:mergeReleaseResources step with "Daemon startup failed" message 上失败

java - ArrayList set(position,object) 方法 RecyclerView 中的 IndexOutOfBound 异常

Android SQLite 列索引

android - 为面向 SDK 22+ 的 Android 库禁用 ART 运行时 (vmSafeMode) 和 dex2oat?

android - 如何在点击时为 ListView 项目设置背景并在其他点击时动态更改

android - 连接安卓设备

android 新样式上下文菜单/对话框

java - 为什么我的 160kb 应用程序背景在运行时变成了 49 MB?

android - 如何测量我的应用程序在 Android 上的功耗?

Android ViewPager 可视化为 "stair"