我怎样才能第二次正确保存我的位图?

How can I save my bitmap correctly for second time?

我想将我的位图保存到缓存目录。 我使用此代码:

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);
    }
}

它工作正常。但是如果我想将不同的 img 保存到相同的路径,就会出错。我的意思是它保存到相同的路径但我看到它是旧图像,但是当我单击图像时我可以看到我第二次保存的正确图像。

也许它来自缓存,但我不想看到旧图像,因为当我想与看到的 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);

我该如何解决?

提前致谢。

这只是一个猜测,但由于您保存了一个新图像(使用旧名称或其他名称,这不相关),您应该对该路径进行媒体扫描,以便媒体提供程序更新为新内容.

参见here

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.
    }
});

在任何情况下都应在新文件保存后调用它。正如我所说,我没有测试过,这只是一个随机猜测。

最后我这样解决了我的问题:

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);
        }