如何正确保存位图的第二次?

6
我希望将位图保存到缓存目录。我使用以下代码:
try {
        File file_d = new File(dir+"screenshot.jpg");
        @SuppressWarnings("unused")
        boolean deleted = file_d.delete();
    } catch (Exception e) {
        // TODO: handle exception
    }

    imagePath = new File(dir+"screenshot.jpg");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }
}

它正常运行。但是如果我想将不同的图片保存到相同的路径,就会出现问题。我的意思是它保存到了相同的路径,但我看到的是旧图片,但当我点击图片时,我可以看到我第二次保存的正确图片。

可能是缓存导致的,但我不想看到旧图片,因为当我想通过WhatsApp共享该图片时,会显示旧图片,但是如果我发送图片,则显示正确的图片。

我想像这个代码一样分享保存的图片到 WhatsApp:

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imagePath));
shareIntent.setType("image/jpeg");
startActivityForResult(Intent.createChooser(shareIntent, getResources().getText(R.string.title_share)),whtsapp_result);

我该怎么修复它?提前感谢您。

最佳实践是,当您保存新图像时,请先从目录中清除以前的图像(同名图像)。 - Zahidul Islam
我在代码中删除了前一个图像,如你所见,它没有起作用? - CompEng
检查 deleted 值。如果图片被删除,则永远不会回来。 - Zahidul Islam
我调试代码,我控制文件被删除,但是当它重新出现时,先前点击的小图像是错误的。 - CompEng
听起来好像当你替换文件时,缓存的缩略图没有被刷新。你应该寻找一种刷新缓存的方法。你在哪里显示这张图片?是在你的代码中还是在另一个应用程序中?提供示例代码会很有帮助。 - Andrei Mărcuţ
显示剩余3条评论
2个回答

3

最后我按照以下方法解决了我的问题:

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, getImageUri(context,bitmap_));
shareIntent.setType("image/jpeg");
startActivityForResult(Intent.createChooser(shareIntent, getResources().getText(R.string.title_share)),whtsapp_result);

v

public Uri getImageUri(Context inContext, Bitmap inImage) {
          ByteArrayOutputStream bytes = new ByteArrayOutputStream();
          inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
          String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "TitleC1", null);
          return Uri.parse(path);
        }

0
这只是一个猜测,但由于您保存了一个新图像(使用旧名称或其他名称都无关紧要),因此您应该对该路径进行媒体扫描,以便媒体提供程序更新新内容。
请参见此处
MediaScannerConnection.scanFile(context, new String[]{imagePath}, null, null);

或者更好的是,等待扫描完成:
MediaScannerConnection.scanFile(context, new String[]{imagePath}, null, new OnScanCompletedListener() {
    @Override
    void onScanCompleted(String path, Uri uri) {
        // Send your intent now.
    }
});

无论如何,这应该在新文件保存调用。正如我所说,我没有测试过,这只是一个随机的猜测。

抱歉,对此感到抱歉 :-) - natario
我该如何删除缩略图? - CompEng

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接