i'm trying to capture image in android 11 device but request is keep cancelled. i have added also. still unable to capture image. pick image from gallery is working. image is not storing in Android/data folder.
i have added val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION) also still unable to create temp file in storage. please provide any solutions
private fun selectImage() {
imageUtils.createImageFile(applicationContext).let {
viewModel.setFileTempPath(it.absolutePath, "doc_name")
startActivityForResult(imageUtils.captureImage(applicationContext, it), 300)
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
300 -> when (resultCode) {
RESULT_OK -> {
Log.d("tmppath", data?.data.toString())
if (data != null && data.data != null) {
val selectedImage: Bitmap =
imageUtils.getBitmap(data.data, this#TaggingActivity)!!
viewModel.dataModel.selectedImagesArrayList.value.let {
if (it == null) {
viewModel.dataModel.selectedImagesArrayList.value = ArrayList()
}
val a = it
a?.add(
ImageDetailsToUpload(
"",
selectedImage,
Constant.CUSTOMER_GEO_TAG,
viewModel.dataModel.documentName.value,
viewModel.commonModel.currentLocation.value!!
)
)
viewModel.dataModel.selectedImagesArrayList.postValue(a)
}
} else {
if (viewModel.dataModel.tmpPath.value != null) {
imageUtils.getBitmapFromPath(viewModel.dataModel.tmpPath.value)
?.let { selectedImage ->
val a = viewModel.dataModel.selectedImagesArrayList.value
a?.add(
ImageDetailsToUpload(
"",
selectedImage,
Constant.CUSTOMER_GEO_TAG,
viewModel.dataModel.documentName.value,
viewModel.commonModel.currentLocation.value!!
)
)
viewModel.dataModel.selectedImagesArrayList.postValue(a)
} ?: run {
viewModel.commonModel.showToastTextView("Sorry Try Again..!")
}
} else {
viewModel.commonModel.showToastTextView("Sorry Try Again..!")
return
}
}
viewModel.dataModel.tmpPath.value = null
}
RESULT_CANCELED -> {
viewModel.setFileTempPath("", "")
Toast.makeText(this,"cancelled",Toast.LENGTH_LONG).show()
}
}
}
//Intent class
fun getCameraIntent(file: File): Intent {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file))
if (Build.VERSION.SDK_INT >= 24) {
try {
val m =
StrictMode::class.java.getMethod("disableDeathOnFileUriExposure")
m.invoke(null)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
} else {
takePictureIntent.putExtra("return-data", true)
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
val pickPhoto = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
val intents: ArrayList<Intent> = arrayListOf()
intents.add(takePictureIntent)
intents.add(pickPhoto)
val chooserIntent = Intent.createChooser(
intents.removeAt(intents.size - 1),
" Document Upload"
)
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(arrayOf<Parcelable>()))
return chooserIntent
}
Related
I'm using google ml kit for face detection, then use bounding Box function to crop faces.
I successfully integrate cameras ,then want to add select from gallery function, which I successfully implement previous training app that I wrote in Java, yet I can find why App written in Kotlin can not identify image Uri from gallery.
I tried multiple methods InputImage.fromBirmap(), InputImage.fromFilePath() and InputImage.fromByteArray("use nv21"), and used Image View to display images with rotation degrees that seems perfect. You can find codes that initiated by on click method below, except InputImage.fromFilePath() and InputImage.fromByteArray("use nv21") which tried first, then delete the codes.
Also thank you before hand.
private fun selectImage() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 11)
}
#RequiresApi(Build.VERSION_CODES.N)
#Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
if (requestCode == 11) {
if (data != null){
val bitmap = getBitmapFromUri(data.data!!)
Log.d(TAG, "onActivityResult: ${data.data!!}")
val inputStream = contentResolver.openInputStream(data.data!!)
val exif = ExifInterface(inputStream!!)
val rotation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL
)
val rotationInDegrees: Int = exifToDegrees(rotation)
inputStream.close()
Log.d(TAG, "onActivityResult: rotation: $rotation")
if (bitmap != null) selectedImageAnalyser(bitmap, rotationInDegrees)
}
}
}
}
private fun exifToDegrees(exifOrientation: Int): Int {
return when (exifOrientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> {
90
}
ExifInterface.ORIENTATION_ROTATE_180 -> {
180
}
ExifInterface.ORIENTATION_ROTATE_270 -> {
270
}
else -> 0
}
}
private fun getBitmapFromUri(uri: Uri): Bitmap? {
var bitmap: Bitmap? = null
try {
bitmap = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O_MR1) {
val source = ImageDecoder.createSource(
contentResolver, uri
)
ImageDecoder.decodeBitmap(source)
} else {
MediaStore.Images.Media.getBitmap(contentResolver, uri)
}
} catch (e: IOException) {
e.printStackTrace()
}
return bitmap
}
private fun selectedImageAnalyser(bitmap: Bitmap, rotationDegree: Int) {
val mBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true)
val inputImage = InputImage.fromBitmap(mBitmap, rotationDegree)
val rotation = inputImage.rotationDegrees
Log.d(TAG, "onActivityResult: rotation: $rotation")
binding!!.ivFace.apply {
visibility = View.VISIBLE
setImageBitmap(inputImage.bitmapInternal)
}
faceDetector.process(inputImage)
.addOnSuccessListener { faces ->
if (faces.isNullOrEmpty()){
val croppedFace = cropToBox(bitmap,faces[0].boundingBox,rotation)
startEnrollDialog(croppedFace)
} else{
Log.d(TAG, "selectedImageAnalyser: face can not identified")
}
}
.addOnFailureListener { Log.d(TAG, "selectedImageAnalyser: \n\t Cause: ${it.cause} \n\t Message: ${it.message}") }
.addOnCompleteListener { }
}
I'trying to open camera with video and photo.This code working correctly but in onActivityResult can't check file type. data.data is null
Here is a code
private fun openCamera() {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val takeVideoIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
val chooserIntent = Intent(Intent.ACTION_CHOOSER)
val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)
val intentArray = arrayOf(takePictureIntent, takeVideoIntent)
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Choose an action")
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray)
startActivityForResult(chooserIntent, CAMERA_STATUS_CODE)
}
onActivityResult code snippet
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val selectedMediaUri = data?.data
if (resultCode == RESULT_OK) {
when (requestCode) {
GALERY_STATUS_CODE -> {
}
CAMERA_STATUS_CODE -> {
val path = data!!.data!!.path
if (path!!.contains("/video/")) {
} else if (path.contains("/images/")) {
}
}
}
}
}
what's a wrong in my code?!
Thanks
I am currently using the following code here:
val cameraRequestCode = 1
val cameraPermissionCode = 1
var imageUri : Uri? = null
#RequiresApi(api = Build.VERSION_CODES.M)
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == cameraRequestCode) {
if (resultCode == Activity.RESULT_OK) {
var stream: FileOutputStream? = null
try {
val photo: Bitmap =
MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
val saveFilePath: String = getRealPathFromURI(imageUri)
stream = FileOutputStream(saveFilePath)
photo.compress(Bitmap.CompressFormat.JPEG, 25, stream)
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(
applicationContext,
"Can't save image !",
Toast.LENGTH_SHORT
).show()
} finally {
try {
if (stream != null) {
stream.close()
Toast.makeText(
applicationContext,
"Image saved successfully !",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
applicationContext,
"Can't save image, try again !",
Toast.LENGTH_SHORT
).show()
}
} catch (e: IOException) {
e.printStackTrace()
}
}
farmersPixImageView.setImageURI(imageUri)
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(applicationContext, "Cancelled", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(applicationContext, "Can't capture image !", Toast.LENGTH_SHORT)
.show()
}
}
}
private fun getRealPathFromURI(contentUri: Uri?): String {
val proj = arrayOf(MediaStore.Images.Media.DATA)
val cursor: Cursor = managedQuery(contentUri, proj, null, null, null)
val column_index: Int = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor.moveToFirst()
return cursor.getString(column_index)
}
#RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
farmersPixImageView.setOnClickListener {
//if system os is Marshmallow or Above, we need to request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED
) {
//permission was not enabled
val permission = arrayOf(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
//show popup to request permission
requestPermissions(permission, cameraPermissionCode)
} else {
val values = ContentValues()
values.put(
MediaStore.Images.Media.TITLE,
"${relativeFileName}_${System.currentTimeMillis()}"
)
values.put(
MediaStore.Images.Media.DISPLAY_NAME,
"${relativeFileName}_${getDate(
System.currentTimeMillis(),
"MM/dd/yyyy hh:mm:ss.SSS"
)}"
)
values.put(MediaStore.Images.Media.DESCRIPTION, "My Photos")
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
imageUri = contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
val cameraIntent =
Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(cameraIntent, cameraRequestCode)
}
}
}
}
I am using this because I could not get the sample from the Official Documentation to work.
I previously used:
values.put(MediaStore.Images.Media.RELATIVE_PATH, relativeLocation)
but it is only available on Android Q onwards.
I also don't know how to use imageUri to save to custom location because it using contentResolver:
imageUri = contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
How do I save the photo on custom location using the above code?
I used this method to get file from uri, it is work fine with all devices but only crash with samsung devices!
fun Activity.getFilePath(uri: Uri): File {
var cursor: Cursor? = null
return try {
val dataArray = arrayOf(MediaStore.Images.Media.DATA)
cursor = contentResolver.query(uri, dataArray, null, null, null)
val index = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
cursor?.moveToFirst()
File(index?.let { cursor?.getString(it) })
} catch (e: Exception) {
throw KotlinNullPointerException("File not founded")
} finally {
cursor?.close()
}
}
get image from gallery
fun Activity.chooseImageFromGallery(withAskPermission: Boolean) {
if (isPermissionsGranted(Manifest.permission.READ_EXTERNAL_STORAGE)) {
val intent = Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST)
} else {
if (withAskPermission && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
PICK_IMAGE_REQUEST)
}
}
}
on Activity result
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == PICK_IMAGE_REQUEST) {
uri = data?.data
file = uri?.let { activity?.getFilePath(it) }
//
}
}
I need help. On my onCreate() I have this code:
takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
setListener(object : DialogGetPhotoFrom.DialogListener {
override fun onTakeFromGallery() {
Log.v("ProjectDetails", "onTakeFromGallery called")
val intent = Intent().apply {
type = "image/*"
action = Intent.ACTION_GET_CONTENT
}
startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
}
override fun onTakePhoto() {
dispatchTakePictureIntent()
}
})
}
projectDetails_pickImage.setOnClickListener { takePhotoDialog?.show(supportFragmentManager) }
An on my onActivityResult, I wrote:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_PICK_IMAGE -> {
Log.v("ProjectDetails", "REQUEST_PICK_IMAGE called")
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
try {
val inputStream = contentResolver.openInputStream(data.data)
val bitMap = BitmapFactory.decodeStream(inputStream)
projectDetails_image.setImageBitmap(bitMap)
// TODO Save image URI to database
} catch (e: Exception) {
Toast.makeText(this, "Can't set background.", Toast.LENGTH_SHORT).show()
}
} else {
Log.v("ProjectDetails", "data is null")
}
}
}
}
}
The problem is, onActivityResult() doesn't fire when an image is selected. What should I do?
Solved it! The solution is to put the codes inside my onTakeGallery() function to a function that belongs to the Activity class. So my code will look like this:
takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
setListener(object : DialogGetPhotoFrom.DialogListener {
override fun onTakeFromGallery() {
dispatchSelectFromGalleryIntent()
}
override fun onTakePhoto() {
dispatchTakePictureIntent()
}
})
}
projectDetails_pickImage.setOnClickListener {
takePhotoDialog?.show(supportFragmentManager)
}
And the extracted codes goes here:
private fun dispatchSelectFromGalleryIntent() {
val intent = Intent().apply {
type = "image/*"
action = Intent.ACTION_GET_CONTENT
}
startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
}