0

画像を保存するために次のコードを使用しています

        FrameLayout mainLayout = (FrameLayout) findViewById(R.id.frame);
            //  File root = Environment.getExternalStorageDirectory();
            //  File file = new File(root, "androidlife.jpg");
//              File file = new File(Environment.getExternalStorageDirectory()
//                        + File.separator + "/test.jpg");
                Random fCount = new Random();
                // for (int i = 0; i < 10; i++) { Comment by Lucifer
                  int roll = fCount.nextInt(600) + 1;
                  //System.out.println(roll);


                File file = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "/test" + String.valueOf(roll) +".jpg" );

                Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
                        mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas c = new Canvas(b);
                mainLayout.draw(c);
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);

                    if (fos != null) {
                        b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                        fos.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            //  }  Comment by Lucifer

画像は完全に保存されますが、保存ボタンを 2 回押すと上書きされます...何が問題なのですか? 任意の提案??

4

4 に答える 4

6
File file = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "/test.jpg");
if(!file.exists()){
    try {
      file.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}else{
    file.delete();
    try {
        file.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
mainLayout.draw(c);
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(file);
    if (fos != null) {
        b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
        fos.close();
    }
} catch (Exception e) {
    e.printStackTrace();
}
于 2012-05-18T02:34:11.803 に答える
2

静的ファイル名を指定しました。

File file = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "/test.jpg");

そのため、毎回、test.jpg という名前で同じ場所に画像を作成します。実装する必要がある唯一のロジックは、ファイル名を動的ファイル名に変更することです。この方法で試すことができます

static int fCount = 0;

File file = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "/test" + String.valueOf(fCount++) +".jpg" );

上記の行は、test0.jpg、test1.jpg などの名前で始まる新しいファイルを毎回作成します。

ただし、これにより、アプリケーションを閉じてアプリケーションを再起動するときに問題が発生する可能性があります。カウンター0からやり直すから。

したがって、ファイル名に乱数を使用することをお勧めします。

于 2012-05-18T02:43:29.823 に答える