Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. /**
  2. * take a picture but check for camera permissions first
  3. */
  4. fun takePicture() {
  5. val permissionGranted = ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
  6. if (permissionGranted) {
  7. openCamera()
  8. } else {
  9. ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_CODE)
  10. }
  11. }
  12.  
  13. /**
  14. * Open the camera after obtaining the permission
  15. */
  16. override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
  17. when (requestCode) {
  18. CAMERA_PERMISSION_CODE -> {
  19. if (grantResults.isEmpty() || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
  20. Log.i("CAMERA", "Permission has been denied by user")
  21. } else {
  22. openCamera()
  23. Log.i("CAMERA", "Permission has been granted by user")
  24. }
  25. }
  26. }
  27. }
  28.  
  29. /**
  30. * Save the picture to the thumbnail after taking it
  31. */
  32. override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
  33. super.onActivityResult(requestCode, resultCode, data)
  34. if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
  35. try {
  36. //Getting the Bitmap from Gallery
  37. val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, this.imageUri) as Bitmap
  38. this.imgThumb!!.setImageBitmap(bitmap)
  39. this.pictureTaken = true
  40. } catch (e:IOException) {
  41. e.printStackTrace()
  42. }
  43. } else {
  44. Toast.makeText(context, "Error loading image", Toast.LENGTH_LONG)
  45. }
  46. }
  47.  
  48. @Throws(IOException::class)
  49. fun createImageFile(): File {
  50. val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
  51. val imageFileName: String = "JPEG_" + timeStamp + "_"
  52. val storageDir: File = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
  53. if(!storageDir.exists()) storageDir.mkdirs()
  54. val imageFile = File.createTempFile(imageFileName, ".jpg", storageDir)
  55. imageFilePath = imageFile.absolutePath
  56. return imageFile
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement