【问题标题】:prevent replacing previous image with new one (android)防止用新图像替换以前的图像(android)
【发布时间】:2014-10-17 10:01:40
【问题描述】:

我正在开发下载图片的壁纸应用程序,但我遇到了图片替换问题。

每当我下载新图像时,它都会被以前的图像替换。

这是我的代码:

public void saveImageToSDCard(Bitmap bitmap) {
        String dirname = "/Amazing Wallpapers/";

        File myDir = new File(Environment
                .getExternalStorageDirectory().getPath() + dirname);

        myDir.mkdirs();

        String str = currentUrl.substring(
                currentUrl.lastIndexOf('/')+1,
                currentUrl.length());

        String fname = "Wallpaper-" + str +  ".jpg";
        File file = new File(myDir, fname);
        if (file.exists())
            file.delete();
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            Toast.makeText(
                    _context,
                    _context.getString(R.string.toast_saved).replace("#",
                            "\"" + pref.getGalleryName() + "\""),
                    Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Wallpaper saved to:" + file.getAbsolutePath());

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(_context,
                    _context.getString(R.string.toast_saved_failed),
                    Toast.LENGTH_SHORT).show();
        }
    }

【问题讨论】:

    标签: android image android-image environment fileoutputstream


    【解决方案1】:

    只需使用当前的Date 时间(以毫秒为单位)作为您的File 的唯一标识符。像这样:

     String str = String.valueOf(System.currentTimeMillis());
    

    我测试了您的代码并且它正在运行。

    【讨论】:

    • 好的,它可以工作,但会产生新问题,问题是现在我可以多次保存相同的图像。但如果它已经存在,我不想多次保存相同的图像
    • @android question 然后,你必须想办法知道哪些文件已经保存并检查它。例如,您的 ViewPager 页面的位置。或文件名。
    • 如果对您有帮助,请接受/支持我的回答。
    猜你喜欢
    • 1970-01-01
    • 2012-11-16
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2016-02-17
    • 2014-03-15
    相关资源
    最近更新 更多