button.setOnClickListener {
saveToGallery()}
这是呼叫电话的按钮 saveToGallery()
功能
private fun saveToGallery()
{
val iv = findViewById<View>(R.id.photo_image) as ImageView
val draw = iv.drawable
val bitmap: Bitmap = draw.toBitmap()
var outstream : FileOutputStream?=null
val sdcard: File = Environment.getExternalStorageDirectory()
val dir = File(sdcard.absolutePath + "/FlickrPics")
dir.mkdirs()
val filename:String = String.format("%d.png",System.currentTimeMillis())
val outFile = File(dir,filename)
try{
outstream = FileOutputStream(outFile)
} catch(e: Exception) {
e.printStackTrace()
}
bitmap.compress(Bitmap.CompressFormat.PNG,100,outstream)
try {
if (outstream != null) {
outstream.flush()
}
}
catch (e: Exception){
e.printStackTrace()
}
try {
if (outstream != null) {
outstream.close()
}
}
catch (e: Exception){
e.printStackTrace()
}
2条答案
按热度按时间snz8szmq1#
除非您显式请求权限,否则它将不起作用,这些是请求权限的代码,只需在主活动中调用setuppermissions()
31moq8wy2#
这条线上有问题
扩展为空
如果你把它放进去试试看
结论:
您的文件不是创建的,它需要权限(在清单和运行时也需要权限)
在清单中添加这两行
请求权限运行时
测试代码: