【发布时间】:2017-10-23 13:49:30
【问题描述】:
我看到很多关于在 android 中将图像保存到画廊的讨论,我想知道 MediaStore 是否仍然是一个很好的方法?
谢谢,
【问题讨论】:
标签: android mediastore
我看到很多关于在 android 中将图像保存到画廊的讨论,我想知道 MediaStore 是否仍然是一个很好的方法?
谢谢,
【问题讨论】:
标签: android mediastore
我从未推荐过这种方法,原因很简单:您不知道该图像会在哪里结束。
相反,将图像保存到某个已知的、可控的位置,然后使用MediaScannerConnection 让MediaStore 知道该图像。如果您让用户控制位置,您的应用只需为未单独配置的用户提供默认位置即可获得奖励积分。
【讨论】:
使用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);
}
});
【讨论】:
由于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)
}
【讨论】: