如何实现拍照按钮并将拍摄照片传递至另一Activity?
Hey there, sorry this has been bugging you for two weeks—let’s get this sorted out! Showing a captured photo in another Activity is totally doable, and I’ll walk you through the most reliable approaches below.
Directly passing large bitmaps between Activities can cause OutOfMemoryErrors, so using a file path is the safest bet. Here's how to do it step by step:
Step 1: Save the Captured Photo to a Local File
When you trigger the camera, first create a dedicated file to save the photo (using your app's private external storage to avoid permission headaches on Android 10+):
private lateinit var currentPhotoPath: String private fun createImageFile(): File { val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date()) val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES) return File.createTempFile( "JPEG_${timeStamp}_", ".jpg", storageDir ).apply { currentPhotoPath = absolutePath // Save the path for later use } }
Then launch the camera intent with this file's URI (using FileProvider to comply with Android's security rules):
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) val photoFile: File? = try { createImageFile() } catch (ex: IOException) { // Handle file creation errors here null } photoFile?.also { val photoURI = FileProvider.getUriForFile( this, "com.your.app.package.fileprovider", // Replace with your app's FileProvider authority it ) takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI) // Use Activity Result API (modern approach) instead of startActivityForResult takePictureLauncher.launch(takePictureIntent) }
Step 2: Pass the File Path to the Second Activity
Once the photo is captured and saved, pass the file path via Intent when launching your target Activity:
// Register the Activity Result Launcher in your onCreate val takePictureLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == RESULT_OK) { // Photo is saved at currentPhotoPath val intent = Intent(this, YourSecondActivity::class.java) intent.putExtra("IMAGE_FILE_PATH", currentPhotoPath) startActivity(intent) } }
Step 3: Load the Image in the Second Activity
Retrieve the path and load the image into an ImageView. For better performance, use an image loading library like Glide or Picasso instead of BitmapFactory directly (to avoid OOM):
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) val imagePath = intent.getStringExtra("IMAGE_FILE_PATH") imagePath?.let { // Option 1: Using BitmapFactory (simpler but riskier for large images) val bitmap = BitmapFactory.decodeFile(it) findViewById<ImageView>(R.id.target_image_view).setImageBitmap(bitmap) // Option 2: Using Glide (recommended for efficiency) // Glide.with(this).load(File(it)).into(findViewById(R.id.target_image_view)) } }
Important Setup: FileProvider
Don't forget to configure FileProvider in your AndroidManifest.xml to allow the camera app to write to your app's private files:
<application ...> <provider android:name="androidx.core.content.FileProvider" android:authorities="com.your.app.package.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider> </application>
Then create res/xml/file_paths.xml to define the directory your FileProvider can access:
<paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-files-path name="captured_photos" path="Pictures" /> </paths>
If you're working with small images (like thumbnails), you can pass the Bitmap directly via Intent, but be warned—this can cause memory issues for high-resolution photos:
// In your first Activity after capturing the photo val bitmap = BitmapFactory.decodeFile(currentPhotoPath) val intent = Intent(this, YourSecondActivity::class.java) intent.putExtra("IMAGE_BITMAP", bitmap) startActivity(intent) // In the second Activity val bitmap = intent.getParcelableExtra<Bitmap>("IMAGE_BITMAP") bitmap?.let { findViewById<ImageView>(R.id.target_image_view).setImageBitmap(it) }
Give these methods a try—chances are the issue was either not saving the photo to a persistent location or mishandling the data transfer between Activities. Let me know if you run into any specific errors!
内容的提问来源于stack exchange,提问作者Bodie

