如何在图库中保存很多imageview副本

时间:2017-08-31 02:40:10

标签: android android-studio imageview save

我正在将imageview保存到图库但是当我保存另一个imageview时,它将替换之前的版本,我不知道为什么忽略file.createNewFile();。如何为imageview保存不同的图像文件?以下代码。

    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RelativeLayout content = (RelativeLayout) findViewById(R.id.dashBoard);
            content.setDrawingCacheEnabled(true);
            Bitmap bitmap = content.getDrawingCache();
            File file = new File(Environment.getExternalStorageDirectory().getPath()+ imagename+ ".png");

            try {
                if (!file.exists()) {
                    file.createNewFile();

                }
                FileOutputStream ostream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 10, ostream);
                ostream.close();
                content.invalidate();
                Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                    e.printStackTrace();

            } finally {
                content.setDrawingCacheEnabled(false);
            }
        }
    });

2 个答案:

答案 0 :(得分:0)

尝试使用UUID.randomUUID()代替imagename 我认为imagename始终是相同的,这就是为什么它取代旧的

答案 1 :(得分:0)

您可以将当前时间作为文件名::

    save.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        RelativeLayout content = (RelativeLayout) findViewById(R.id.dashBoard);
        content.setDrawingCacheEnabled(true);
        Bitmap bitmap = content.getDrawingCache();
        Date d = new Date();
        CharSequence imagename  = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
        File file = new File(Environment.getExternalStorageDirectory().getPath()+ imagename+ ".png");

        try {
            if (!file.exists()) {
                file.createNewFile();

            }
            FileOutputStream ostream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 10, ostream);
            ostream.close();
            content.invalidate();
            Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
                e.printStackTrace();

        } finally {
            content.setDrawingCacheEnabled(false);
        }
    }
});