Android Studio 获取照片真实路径并保存到 ImageView - 详细步骤和代码示例
要获取照片的真实路径并保存,可以使用以下步骤:\n\n1. 在 AndroidManifest.xml 文件中添加以下权限:\nxml\n<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />\n\n\n2. 在代码中使用以下方法获取照片的真实路径:\njava\npublic String getRealPathFromURI(Uri contentUri) {\n String[] projection = {MediaStore.Images.Media.DATA};\n Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);\n if (cursor == null) {\n return null;\n }\n int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);\n cursor.moveToFirst();\n String path = cursor.getString(column_index);\n cursor.close();\n return path;\n}\n\n\n3. 在保存照片时,调用上述方法获取真实路径:\njava\nUri imageUri = data.getData();\nString imagePath = getRealPathFromURI(imageUri);\n\n\n4. 将真实路径保存到 SharedPreferences 中:\njava\nSharedPreferences sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);\nSharedPreferences.Editor editor = sharedPref.edit();\neditor.putString("imagePath", imagePath);\neditor.apply();\n\n\n5. 在取出路径并显示照片时,从 SharedPreferences 中获取路径:\njava\nSharedPreferences sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);\nString imagePath = sharedPref.getString("imagePath", "");\n\nImageView imageView = findViewById(R.id.imageView);\nBitmap bitmap = BitmapFactory.decodeFile(imagePath);\nimageView.setImageBitmap(bitmap);\n\n\n注意事项:\n- 要在设备上运行时,需要获取存储权限。\n- 为了避免在 Android 10 及以上版本上出现问题,建议使用 MediaStore API 来访问媒体文件。
原文地址: https://www.cveoy.top/t/topic/pT6P 著作权归作者所有。请勿转载和采集!