【问题标题】:Should we still use MediaStore.Images.Media.insertImage() method?我们还应该使用 MediaStore.Images.Media.insertImage() 方法吗?
【发布时间】:2017-10-23 13:49:30
【问题描述】:

我看到很多关于在 android 中将图像保存到画廊的讨论,我想知道 MediaStore 是否仍然是一个很好的方法?

谢谢,

【问题讨论】:

    标签: android mediastore


    【解决方案1】:

    我从未推荐过这种方法,原因很简单:您不知道该图像会在哪里结束。

    相反,将图像保存到某个已知的、可控的位置,然后使用MediaScannerConnectionMediaStore 知道该图像。如果您让用户控制位置,您的应用只需为未单独配置的用户提供默认位置即可获得奖励积分。

    【讨论】:

      【解决方案2】:

      使用MediaStore.Images.Media.insertImage(...) 你最终会得到两个文件。以下是 CommonsWare 建议的方法:

      // ...
      // (save your image as usual to your custom location)
      // ...
      
      // notify mediascanner of the new image
      MediaScannerConnection.scanFile(getApplicationContext(),
                                  new String[] { yourFilePath }, null,
                                  new MediaScannerConnection.OnScanCompletedListener() {
                                      public void onScanCompleted(String path, Uri uri) {
                                          Log.i("ExternalStorage", "Scanned " + path + ":");
                                          Log.i("ExternalStorage", "-> uri=" + uri);
                                      }
                                  });
      

      【讨论】:

        【解决方案3】:

        由于MediaStore.Images.Media.insertImage()这个方法已弃用,最好使用新的方法,例如:

        val mDrawable: Drawable? = baseContext.getDrawable(id)
        val mbitmap = (mDrawable as BitmapDrawable).bitmap
        val mfile = File(externalCacheDir, "myimage.PNG")
                try {
                    val outStream = FileOutputStream(mfile)
                    mbitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream)
                    outStream.flush()
                    outStream.close()
                } catch (e: Exception) {
                    throw RuntimeException(e)
                }
        

        【讨论】:

          猜你喜欢
          • 2010-10-20
          • 2012-04-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-13
          • 2014-04-09
          • 1970-01-01
          • 2021-10-20
          相关资源
          最近更新 更多