एंड्रॉइड में कैमरा इंटेंट के साथ फोटो कैप्चर
यह उदाहरण दर्शाता है कि सिस्टम कैमरा ऐप का उपयोग करके फोटो कैसे ली जाए और परिणाम को ImageView में प्रदर्शित किया जाए।
चरण 1: नया प्रोजेक्ट बनाएं
एंड्रॉइड स्टूडियो में File → New Project चुनें।
चरण 2: लेआउट (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/imageView"
android:layout_centerInParent="true"
android:layout_marginBottom="10dp"
android:text="नीचे बटन पर क्लिक करके कैमरे से फोटो लें"
android:textAlignment="center"
android:textColor="@android:color/holo_purple"
android:textSize="16sp"
android:textStyle="bold" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_above="@id/btnCaptureImage"
android:layout_marginTop="16dp"
android:scaleType="centerCrop"
android:src="@drawable/ic_baseline_image_24"
android:background="@android:color/darker_gray"
android:contentDescription="कैप्चर की गई छवि" />
<Button
android:id="@+id/btnCaptureImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="फोटो लें"
android:textSize="18sp"
android:padding="16dp" />
</RelativeLayout>
चरण 3: MainActivity.kt (आधुनिक Activity Result API)
import android.Manifest
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity() {
private lateinit var button: Button
private lateinit var imageView: ImageView
private var imageUri: Uri? = null
// आधुनिक अनुमति अनुरोध
private val requestCameraPermission = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) {
openCamera()
} else {
Toast.makeText(this, "कैमरा अनुमति अस्वीकृत", Toast.LENGTH_SHORT).show()
}
}
// आधुनिक कैमरा इंटेंट परिणाम
private val takePicture = registerForActivityResult(
ActivityResultContracts.TakePicture()
) { success ->
if (success) {
imageUri?.let { uri ->
imageView.setImageURI(uri)
Toast.makeText(this, "फोटो सहेजी गई", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "फोटो लेने में विफल", Toast.LENGTH_SHORT).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
imageView = findViewById(R.id.imageView)
button = findViewById(R.id.btnCaptureImage)
button.setOnClickListener {
checkAndRequestPermission()
}
}
private fun checkAndRequestPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
openCamera()
} else {
requestCameraPermission.launch(Manifest.permission.CAMERA)
}
}
private fun openCamera() {
// MediaStore में छवि के लिए एंट्री बनाएं
val values = ContentValues().apply {
put(MediaStore.Images.Media.TITLE, "नई फोटो ${System.currentTimeMillis()}")
put(MediaStore.Images.Media.DESCRIPTION, "कैमरा ऐप से")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/MyCameraApp")
}
}
imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
imageUri?.let { uri ->
takePicture.launch(uri)
} ?: run {
Toast.makeText(this, "छवि URI बनाने में विफल", Toast.LENGTH_SHORT).show()
}
}
}
चरण 4: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.cameraapp">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
<uses-feature android:name="android.hardware.camera.flash" android:required="false" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Android 10+ के लिए फ़ाइल प्रदाता (वैकल्पिक, MediaStore उपयोग कर रहे हैं) -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
</manifest>
चरण 5: file_paths.xml (res/xml/file_paths.xml) - FileProvider के लिए
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="https://schemas.android.com/apk/res/android">
<external-files-path name="my_images" path="Pictures/MyCameraApp/" />
<external-path name="external" path="." />
</paths>
लीगेसी दृष्टिकोण (startActivityForResult - अप्रचलित):
// पुराना तरीका (अप्रचलित)
private val CAMERA_REQUEST = 1888
button.setOnClickListener {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, CAMERA_REQUEST)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
val photo = data?.extras?.get("data") as? Bitmap
photo?.let { imageView.setImageBitmap(it) }
}
}
आधुनिक बनाम लीगेसी तुलना:
| पहलू | लीगेसी (startActivityForResult) | आधुनिक (Activity Result API) |
|---|---|---|
| कोड संरचना | अनुरोध कोड, onActivityResult में परिणाम | कॉलबैक-आधारित, प्रकार-सुरक्षित |
| जीवनचक्र जागरूक | नहीं | हाँ |
| कॉन्फ़िगरेशन परिवर्तन | मैन्युअल हैंडलिंग | स्वचालित |
| एकाधिक अनुरोध | अनुरोध कोड प्रबंधन | अलग लॉन्चर प्रति अनुरोध |
उन्नत: CameraX लाइब्रेरी (अनुशंसित उत्पादन के लिए)
// build.gradle
dependencies {
def camerax_version = "1.3.0"
implementation "androidx.camera:camera-core:${camerax_version}"
implementation "androidx.camera:camera-camera2:${camerax_version}"
implementation "androidx.camera:camera-lifecycle:${camerax_version}"
implementation "androidx.camera:camera-view:${camerax_version}"
}
// CameraX उपयोग
val imageCapture = ImageCapture.Builder().build()
val photoFile = File(outputDir, "photo_${System.currentTimeMillis()}.jpg")
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
imageCapture.takePicture(
outputOptions,
ContextCompat.getMainExecutor(this),
object : ImageCapture.OnImageSavedCallback {
override fun onError(exc: ImageCaptureException) {
// त्रुटि प्रबंधन
}
override fun onImageSaved(output: ImageCapture.OutputFileResults) {
// सफलता - imageView.setImageURI(photoFile.toUri())
}
}
)
⚠️ महत्वपूर्ण: रियल डिवाइस पर टेस्ट करें
कैमरा कार्यक्षमता एमुलेटर में सीमित या अनुपलब्ध होती है। हमेशा भौतिक डिवाइस पर टेस्ट करें।