Skip to content

Instantly share code, notes, and snippets.

@dan085
Created February 1, 2020 21:06
Show Gist options
  • Save dan085/c04133f4654f891ebc38b7ddfcbca558 to your computer and use it in GitHub Desktop.
Save dan085/c04133f4654f891ebc38b7ddfcbca558 to your computer and use it in GitHub Desktop.
seleccionar foto de la galerya o usar la camara
import android.content.BroadcastReceiver
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Parcelable
import android.os.StrictMode
import android.provider.MediaStore
import android.util.Log
import androidx.core.content.FileProvider
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.*
class ImagePicker {
inner class ApplicationStatusNotification : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
for (key in intent.extras!!.keySet()) {
Log.d(javaClass.simpleName, " " + intent.extras!!.get(key)!!)
}
}
}
companion object {
private val TEMP_IMAGE_NAME = "tempImage"
fun getPickImageIntent(context: Context): Intent? {
if (Build.VERSION.SDK_INT > 23) {
val builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
}
var chooserIntent: Intent? = null
var intentList: MutableList<Intent> = ArrayList()
val pickIntent = Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
val takePhotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
takePhotoIntent.putExtra("return-data", true)
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)))
intentList = addIntentsToList(context, intentList, pickIntent)
intentList = addIntentsToList(context, intentList, takePhotoIntent)
if (intentList.size > 0) {
chooserIntent = Intent.createChooser(intentList.removeAt(intentList.size - 1), context.getString(R.string.Select_Option))//,pendingIntent.getIntentSender());
chooserIntent!!.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toTypedArray<Parcelable>())
}
return chooserIntent
}
fun getPickImageIntent_gallery(context: Context): Intent? {
if (Build.VERSION.SDK_INT > 23) {
val builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
}
var chooserIntent: Intent? = null
var intentList: MutableList<Intent> = ArrayList()
val pickIntent = Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
intentList = addIntentsToList(context, intentList, pickIntent)
if (intentList.size > 0) {
chooserIntent = Intent.createChooser(intentList.removeAt(intentList.size - 1), context.getString(R.string.Select_Option))//,pendingIntent.getIntentSender());
chooserIntent!!.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toTypedArray<Parcelable>())
}
return chooserIntent
}
fun getPickImageIntent_photo(): Intent {
if (Build.VERSION.SDK_INT > 23) {
val builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
}
val takePhotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
takePhotoIntent.putExtra("return-data", true)
return takePhotoIntent
}
private fun addIntentsToList(context: Context, list: MutableList<Intent>, intent: Intent): MutableList<Intent> {
val resInfo = context.packageManager.queryIntentActivities(intent, 0)
for (resolveInfo in resInfo) {
val packageName = resolveInfo.activityInfo.packageName
val targetedIntent = Intent(intent)
targetedIntent.setPackage(packageName)
list.add(targetedIntent)
//Log.d(TAG, "Intent: " + intent.getAction() + " package: " + packageName);
}
return list
}
fun getTempFile(context: Context): File {
val imageFile = File(context.externalCacheDir, TEMP_IMAGE_NAME)
imageFile.parentFile!!.mkdirs()
return imageFile
}
fun getOutput(result: Intent): Uri? {
return result.getParcelableExtra(MediaStore.EXTRA_OUTPUT)
}
fun persistImage(context: Context,bitmap: Bitmap): String {
val filesDir: File = context.cacheDir
val timeStamp: String = SimpleDateFormat(
"yyyyMMdd_HHmmss",
Locale.getDefault()
).format(Date())
val imageFileName = "IMG_" + timeStamp
val imageFile = File(filesDir, "$imageFileName.jpg")
val os: OutputStream
try {
os = FileOutputStream(imageFile)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os)
os.flush()
os.close()
return imageFile.absolutePath
} catch (e: Exception) {
return ""
}
}
/**
fun getImageUri(
inContext: Context,
inImage: Bitmap
): Uri? {
val timeStamp: String = SimpleDateFormat(
"yyyyMMdd_HHmmss",
Locale.getDefault()
).format(Date())
val imageFileName = "IMG_" + timeStamp
val bytes = ByteArrayOutputStream()
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path: String =
MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, imageFileName, null)
return Uri.parse(path)
}**/
/// @param folderName can be your app's name
fun saveImage( context: Context,bitmap: Bitmap) : Uri? {
if (Build.VERSION.SDK_INT >= 29) {
val values = contentValues()
values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/" + context.resources.getString(R.string.beambask))
values.put(MediaStore.Images.Media.IS_PENDING, true)
// RELATIVE_PATH and IS_PENDING are introduced in API 29.
val uri: Uri? = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
if (uri != null) {
saveImageToStream(bitmap, context.contentResolver.openOutputStream(uri))
values.put(MediaStore.Images.Media.IS_PENDING, false)
context.contentResolver.update(uri, values, null, null)
return uri
}
} else {
/** val directory = File(Environment.getExternalStorageDirectory().toString() + "/" + "Bimbask" + "/" + "Pictures" + "/")
// getExternalStorageDirectory is deprecated in API 29
if (!directory.exists()) {
directory.mkdirs()
}**/
val filesDir: File = context.cacheDir
val timeStamp: String = SimpleDateFormat(
"yyyyMMdd_HHmmss",
Locale.getDefault()
).format(Date())
val imageFileName = "IMG_" + timeStamp
val imageFile = File(filesDir, "$imageFileName.jpg")
val os: OutputStream
try {
os = FileOutputStream(imageFile)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os)
os.flush()
os.close()
// val path: String = MediaStore.Images.Media.insertImage(context.contentResolver, imageFile.absolutePath, imageFile.name, imageFile.name)
/** val values = ContentValues()
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg")
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATA, imageFile.absolutePath)**/
// .DATA is deprecated in API 29
// val path: Uri? = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
return FileProvider.getUriForFile(context, "com.bimbask.ccp.fileprovider", imageFile)
} catch (e: Exception) {
return null
}
}
return null
}
private fun contentValues() : ContentValues {
val values = ContentValues()
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg")
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
return values
}
private fun saveImageToStream(bitmap: Bitmap, outputStream: OutputStream?) {
if (outputStream != null) {
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
outputStream.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
}
@dan085
Copy link
Author

dan085 commented Feb 1, 2020

para llamar la funcion utilizo

startActivityForResult(ImagePicker.getPickImageIntent_photo(), GALLERY_LOLLIPOP_INTENT_CALLED_PHOTO)

@dan085
Copy link
Author

dan085 commented Feb 1, 2020

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == GALLERY_LOLLIPOP_INTENT_CALLED && resultCode == Activity.RESULT_OK) {
        startCroppy(data!!.data!!)
    }else if(requestCode == GALLERY_LOLLIPOP_INTENT_CALLED_PHOTO && resultCode == Activity.RESULT_OK){
        val imageBitmap = data!!.extras!!["data"] as Bitmap?
        val path_photo_temp_file=  ImagePicker.saveImage(this,imageBitmap!!)
        startCroppy(path_photo_temp_file!!)

    }else if (requestCode == RC_CROP_IMAGE) {


        thread(start = true) {
            try {
                handleCrop_croppy(data!!.data!!.path!!, resultCode)
            }catch (ee:kotlin.KotlinNullPointerException){
                ee.printStackTrace()
            }

        }


    }
 

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment