我用下面的代码保存一个图像。
val cw = ContextWrapper(applicationContext)
val directory =
cw.getDir("imageDir", Context.MODE_PRIVATE)
val file = File(directory, Utility().replaceSpaces(categoryName) + ".png")
if (!file.exists()) {
Log.d("path", file.toString())
var fos: FileOutputStream? = null
try {
fos = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
fos.flush()
fos.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
我使用以下代码检索图像。
val uri =
if (category.isEmpty()) "@drawable/appicon"
else "@drawable/${Utility().replaceSpaces(category)}"
var image = resources.getIdentifier(uri, null, packageName)
if (image == 0)
image = resources.getIdentifier("@drawable/appicon", null, packageName)
val imageView = ImageView(this)
检索图像时,图像始终为0
我正在用下面的代码保存一个图像
您不需要ContextWrapper
。
我使用以下代码检索图像
对于试图获取资源标识符来说,这是一些相当奇怪的代码。 不能在运行时修改资源,并且您保存的图像不是资源。
相反,请以与在第一个代码段中相同的方式创建file
对象。 然后,将file
对象交给图像加载库,例如Glide或Picasso。 他们可以读取并解码后台线程上的图像,然后用结果更新您的ImageView
。