Mehedi Hassan Piash | Senior Software Engineer | Android | iOS | KMP | Ktor | Jetpack Compose | React-Native.

July 28, 2021

Image picker and convert uri to file

July 28, 2021 Posted by Piash , No comments

 1. Fetch uri with https://github.com/Dhaval2404/ImagePicker

 ImagePicker.with(this)  
     .compress(1024)     //Final image size will be less than 1 MB(Optional)  
     .maxResultSize(1080, 1080) //Final image resolution will be less than 1080 x 1080(Optional)  
     .createIntent { intent ->  
       startForProfileImageResult.launch(intent)  
     }  
 private val startForProfileImageResult =  
   registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->  
     val resultCode = result.resultCode  
     val data = result.data  
     if (resultCode == Activity.RESULT_OK) {  
       //Image Uri will not be null for RESULT_OK  
       val fileUri = data?.data!!  
       mProfileUri = fileUri  
       imgProfile.setImageURI(fileUri)  
     } else if (resultCode == ImagePicker.RESULT_ERROR) {  
       Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show()  
     } else {  
       Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show()  
     }  
   }  

 2. Convert Uri to file using the following function 

  private fun fileFromContentUri(context: Context, contentUri: Uri): File {  
     // Preparing Temp file name  
     val fileExtension = getFileExtension(context, contentUri)  
     val fileName = "temp_file" + if (fileExtension != null) ".$fileExtension" else ""  
     // Creating Temp file  
     val tempFile = File(context.cacheDir, fileName)  
     tempFile.createNewFile()  
     try {  
       val oStream = FileOutputStream(tempFile)  
       val inputStream = context.contentResolver.openInputStream(contentUri)  
       inputStream?.let {  
         copy(inputStream, oStream)  
       }  
       oStream.flush()  
     } catch (e: Exception) {  
       e.printStackTrace()  
     }  
     return tempFile  
   }  
 private fun getFileExtension(context: Context, uri: Uri): String? {  
     val fileType: String? = context.contentResolver.getType(uri)  
     return MimeTypeMap.getSingleton().getExtensionFromMimeType(fileType)  
   }  
  @Throws(IOException::class)  
   private fun copy(source: InputStream, target: OutputStream) {  
     val buf = ByteArray(8192)  
     var length: Int  
     while (source.read(buf).also { length = it } > 0) {  
       target.write(buf, 0, length)  
     }  
   }  

0 comments:

Post a Comment