【问题标题】:How can I save my bitmap correctly for second time?如何第二次正确保存位图?
【发布时间】:2016-06-05 11:36:23
【问题描述】:

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

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

我该如何解决?

提前致谢。

【问题讨论】:

  • 最佳做法是在保存新图像时首先从目录中清除之前的图像(同名图像)。
  • 我删除了你在我的代码中看到的上一个图像,它不起作用?
  • 检查deleted 值。如果图像被删除,那么它将永远不会回来。
  • 我调试了代码,我控制了它被删除的文件,但是当回来时,它之前点击的小图像是错误的
  • 当您替换文件时,听起来缓存的缩略图没有被刷新。您应该寻找一种方法来刷新缓存。你在哪里显示图像?是在您的代码中还是在其他应用程序中?示例代码会很有用。

标签: android android-layout android-imageview android-bitmap android-file


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 对不起 :-)
    • 如何删除缩略图
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 2012-09-02
    相关资源
    最近更新 更多