android - 如何将图像保存到kotlin中的画廊
问题描述
我正在开发一个从用户图库添加图像然后再次保存的项目,我使用下面的代码让用户选择图像并将其添加到应用程序中并且它有效但我不知道如何保存图像(稍后我将添加将编辑图像的按钮,所以我想知道如何在编辑后保存它)
lateinit var photo: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
photo = findViewById<ImageView>(R.id.photo);
val upload = findViewById<Button>(R.id.upload)
val getaction = registerForActivityResult(
ActivityResultContracts.GetContent(),
ActivityResultCallback { uri ->
photo.setImageURI(uri)
}
)
upload.setOnClickListener {
getaction.launch("image/*")
}
解决方案
//使用下面的代码将uri保存到位图:
//Create a bitmap using the uri from your code
Bitmap bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver() , Uri.parse(paths));
// 获得位图后,您可以将其保存到存储中,请记住您可能需要权限,具体取决于您要保存图像的位置。
//Code to save bitmap to image on storage, filePath will be the path you wish to save it to.
try {
File file = new File(filePath);
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
LOG.i(null, "Save file error!");
return false;
}
推荐阅读
- android - 活动结束后,BroadcastReceiver 不再触发
- laravel - Laravel:Amazon Web Service 将时区更改为 UTC
- vuejs2 - vuejs 动态渲染图像
- c# - msbuild 不会在发布配置中构建
- django - Django:尝试实现不区分大小写的用户名但不工作
- android - CMake 错误:在 EnableLanguage 之后未设置 CMAKE_C_COMPILER
- linq - 在 DbContext 上构建过滤器
- javascript - 使用 node js、express 和 OracleDB 创建 API
- unix - PL/I 程序中的 z/OS MVS 和 z/OS UNIX 互操作?
- android - 数据未显示在列表中