├── .gitignore ├── CONTRIBUTING.md ├── CameraXBasic ├── .gitignore ├── README.md ├── app │ ├── .gitignore │ ├── build.gradle │ └── src │ │ ├── main │ │ ├── AndroidManifest.xml │ │ ├── ic_launcher-web.png │ │ ├── java │ │ │ └── com │ │ │ │ └── android │ │ │ │ └── example │ │ │ │ └── cameraxbasic │ │ │ │ ├── MainActivity.kt │ │ │ │ ├── fragments │ │ │ │ ├── CameraFragment.kt │ │ │ │ ├── GalleryFragment.kt │ │ │ │ ├── PermissionsFragment.kt │ │ │ │ ├── PhotoFragment.kt │ │ │ │ ├── Renderer.kt │ │ │ │ └── TextureDrawer.kt │ │ │ │ └── utils │ │ │ │ ├── AutoFitPreviewBuilder.kt │ │ │ │ ├── ImageUtils.kt │ │ │ │ └── ViewExtensions.kt │ │ └── res │ │ │ ├── color │ │ │ ├── selector_button_text.xml │ │ │ └── selector_ic.xml │ │ │ ├── drawable │ │ │ ├── button_round_corners.xml │ │ │ ├── ic_back.xml │ │ │ ├── ic_delete.xml │ │ │ ├── ic_launcher_background.xml │ │ │ ├── ic_outer_circle.xml │ │ │ ├── ic_photo.xml │ │ │ ├── ic_share.xml │ │ │ ├── ic_shutter.xml │ │ │ ├── ic_shutter_focused.xml │ │ │ ├── ic_shutter_normal.xml │ │ │ ├── ic_shutter_pressed.xml │ │ │ └── ic_switch.xml │ │ │ ├── layout-land │ │ │ └── camera_ui_container.xml │ │ │ ├── layout │ │ │ ├── activity_main.xml │ │ │ ├── camera_ui_container.xml │ │ │ ├── fragment_camera.xml │ │ │ └── fragment_gallery.xml │ │ │ ├── mipmap-anydpi-v26 │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ │ ├── mipmap-hdpi │ │ │ ├── ic_launcher.png │ │ │ ├── ic_launcher_foreground.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ ├── ic_launcher.png │ │ │ ├── ic_launcher_foreground.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ ├── ic_launcher.png │ │ │ ├── ic_launcher_foreground.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ ├── ic_launcher.png │ │ │ ├── ic_launcher_foreground.png │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ ├── ic_launcher.png │ │ │ ├── ic_launcher_foreground.png │ │ │ └── ic_launcher_round.png │ │ │ ├── navigation │ │ │ └── nav_graph.xml │ │ │ ├── values-v28 │ │ │ └── styles.xml │ │ │ ├── values │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── ic_launcher_background.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ │ └── xml │ │ │ └── file_paths.xml │ │ └── test │ │ └── java │ │ └── com │ │ └── android │ │ └── example │ │ └── cameraxbasic │ │ └── MainInstrumentedTest.kt ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Mac files 6 | .DS_Store 7 | 8 | # files for the dex VM 9 | *.dex 10 | 11 | # Java class files 12 | *.class 13 | 14 | # generated files 15 | bin/ 16 | gen/ 17 | 18 | # Ignore gradle files 19 | .gradle/ 20 | build/ 21 | 22 | # Local configuration file (sdk path, etc) 23 | local.properties 24 | 25 | # Proguard folder generated by Eclipse 26 | proguard/ 27 | proguard-project.txt 28 | 29 | # Eclipse files 30 | .project 31 | .classpath 32 | .settings/ 33 | 34 | # Android Studio/IDEA 35 | *.iml 36 | .idea 37 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement 9 | (CLA). 10 | 11 | * If you are an individual writing original source code and you're sure you 12 | own the intellectual property, then you'll need to sign an [individual CLA] 13 | (https://developers.google.com/open-source/cla/individual). 14 | * If you work for a company that wants to allow you to contribute your work, 15 | then you'll need to sign a [corporate CLA] 16 | (https://developers.google.com/open-source/cla/corporate). 17 | 18 | Follow either of the two links above to access the appropriate CLA and 19 | instructions for how to sign and return it. Once we receive it, we'll be able to 20 | accept your pull requests. 21 | 22 | ## Contributing A Patch 23 | 24 | 1. Submit an issue describing your proposed change to the repo in question. 25 | 1. The repo owner will respond to your issue promptly. 26 | 1. If your proposed change is accepted, and you haven't already done so, sign a 27 | Contributor License Agreement (see details above). 28 | 1. Fork the desired repo, develop and test your code changes. 29 | 1. Ensure that your code adheres to the existing style in the sample to which 30 | you are contributing. Refer to the 31 | [Google Cloud Platform Samples Style Guide] 32 | (https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the 33 | recommended coding standards for this organization. 34 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 35 | 1. Submit a pull request. 36 | 37 | -------------------------------------------------------------------------------- /CameraXBasic/.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | app/release 3 | *.apk 4 | *.ap_ 5 | 6 | # Files for the ART/Dalvik VM 7 | *.dex 8 | 9 | # Java class files 10 | *.class 11 | 12 | # Generated files 13 | bin/ 14 | gen/ 15 | out/ 16 | 17 | # Gradle files 18 | .gradle/ 19 | build/ 20 | 21 | # Local configuration file (sdk path, etc) 22 | local.properties 23 | 24 | # Proguard folder generated by Eclipse 25 | proguard/ 26 | 27 | # Log Files 28 | *.log 29 | 30 | # Android Studio Navigation editor temp files 31 | .navigation/ 32 | 33 | # Android Studio captures folder 34 | captures/ 35 | 36 | # IntelliJ 37 | *.iml 38 | .idea/* 39 | !.idea/runConfigurations 40 | 41 | # Keystore files 42 | *.jks 43 | 44 | # External native build folder generated in Android Studio 2.2 and later 45 | .externalNativeBuild 46 | 47 | # Google Services (e.g. APIs or Firebase) 48 | google-services.json 49 | 50 | # Freeline 51 | freeline.py 52 | freeline/ 53 | freeline_project_description.json 54 | 55 | # fastlane 56 | fastlane/report.xml 57 | fastlane/Preview.html 58 | fastlane/screenshots 59 | fastlane/test_output 60 | fastlane/readme.md 61 | -------------------------------------------------------------------------------- /CameraXBasic/README.md: -------------------------------------------------------------------------------- 1 | # CameraXbasic 2 | 3 | CameraXbasic aims to demonstrate how to use CameraX APIs written in Kotlin. 4 | 5 | ## Build 6 | 7 | To build the app directly from the command line, run: 8 | ```sh 9 | ./gradlew assembleDebug 10 | ``` 11 | 12 | ## Test 13 | 14 | Unit testing and instrumented device testing share the same code. To test the app using Roboelectric, no device required, run: 15 | ```sh 16 | ./gradlew test 17 | ``` 18 | 19 | To run the same tests in an Android device connected via ADB, run: 20 | ```sh 21 | ./gradlew connectedAndroidTest 22 | ``` 23 | 24 | Alternatively, test running configurations can be added to Android Studio for convenience (and a nice UI). To do that: 25 | 1. Go to: `Run` > `Edit Configurations` > `Add New Configuration`. 26 | 1. For Roboelectric select `Android JUnit`, for connected device select `Android Instrumented Tests`. 27 | 1. Select `app` module and `com.android.example.cameraxbasic.MainInstrumentedTest` class. 28 | 1. Optional: Give the run configuration a name, like `test roboelectric` or `test device` 29 | -------------------------------------------------------------------------------- /CameraXBasic/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | .idea -------------------------------------------------------------------------------- /CameraXBasic/app/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'com.android.application' 18 | apply plugin: 'kotlin-android' 19 | apply plugin: 'kotlin-android-extensions' 20 | 21 | android { 22 | compileSdkVersion 28 23 | defaultConfig { 24 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 25 | applicationId "com.android.example.cameraxbasic" 26 | minSdkVersion 21 27 | targetSdkVersion 28 28 | versionCode 1 29 | versionName "1.0.0" 30 | } 31 | 32 | compileOptions { 33 | sourceCompatibility rootProject.ext.java_version 34 | targetCompatibility rootProject.ext.java_version 35 | } 36 | 37 | buildTypes { 38 | release { 39 | minifyEnabled false 40 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 41 | } 42 | } 43 | 44 | // Set the source of tests to same for both Unit and Instrumented tests 45 | sourceSets { 46 | String sharedTestDir = 'src/test/java' 47 | test { 48 | java.srcDir sharedTestDir 49 | } 50 | androidTest { 51 | java.srcDir sharedTestDir 52 | } 53 | } 54 | 55 | // Necessary for Roboelectric (Unit tests) 56 | testOptions { 57 | unitTests { 58 | includeAndroidResources = true 59 | } 60 | } 61 | } 62 | 63 | dependencies { 64 | // Kotlin lang 65 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" 66 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1' 67 | 68 | // AndroidX libraries 69 | implementation 'androidx.appcompat:appcompat:1.0.2' 70 | implementation 'androidx.core:core-ktx:1.0.1' 71 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 72 | 73 | // Lifecycle and LiveData 74 | def lifecycle_version = '2.0.0' 75 | implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version" 76 | implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version" 77 | implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version" 78 | implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version" 79 | 80 | // Navigation library 81 | def nav_version = "2.0.0" 82 | implementation "androidx.navigation:navigation-fragment-ktx:$nav_version" 83 | implementation "androidx.navigation:navigation-ui-ktx:$nav_version" 84 | 85 | // CameraX 86 | def camerax_version = "1.0.0-alpha01" 87 | implementation "androidx.camera:camera-core:${camerax_version}" 88 | implementation "androidx.camera:camera-camera2:${camerax_version}" 89 | 90 | // Glide 91 | implementation 'com.github.bumptech.glide:glide:4.9.0' 92 | annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0' 93 | 94 | // Unit testing 95 | testImplementation 'androidx.test.ext:junit:1.1.0' 96 | testImplementation 'androidx.test:rules:1.1.1' 97 | testImplementation 'androidx.test:runner:1.1.1' 98 | testImplementation 'androidx.test.espresso:espresso-core:3.1.1' 99 | testImplementation "org.robolectric:robolectric:4.1" 100 | 101 | // Instrumented testing 102 | androidTestImplementation 'androidx.test.ext:junit:1.1.0' 103 | androidTestImplementation 'androidx.test:rules:1.1.1' 104 | androidTestImplementation 'androidx.test:runner:1.1.1' 105 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' 106 | } 107 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 75 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/ic_launcher-web.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/ic_launcher-web.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/MainActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.example.cameraxbasic 18 | 19 | import android.content.Context 20 | import android.os.Bundle 21 | import android.view.KeyEvent 22 | import androidx.appcompat.app.AppCompatActivity 23 | import java.io.File 24 | import androidx.localbroadcastmanager.content.LocalBroadcastManager 25 | import android.content.Intent 26 | import android.widget.FrameLayout 27 | import com.android.example.cameraxbasic.utils.FLAGS_FULLSCREEN 28 | 29 | const val KEY_EVENT_ACTION = "key_event_action" 30 | const val KEY_EVENT_EXTRA = "key_event_extra" 31 | private const val IMMERSIVE_FLAG_TIMEOUT = 500L 32 | 33 | /** 34 | * Main entry point into our app. This app follows the single-activity pattern, and all 35 | * functionality is implemented in the form of fragments. 36 | */ 37 | class MainActivity : AppCompatActivity() { 38 | private lateinit var container: FrameLayout 39 | 40 | override fun onCreate(savedInstanceState: Bundle?) { 41 | super.onCreate(savedInstanceState) 42 | setContentView(R.layout.activity_main) 43 | container = findViewById(R.id.fragment_container) 44 | } 45 | 46 | override fun onResume() { 47 | super.onResume() 48 | // Before setting full screen flags, we must wait a bit to let UI settle; otherwise, we may 49 | // be trying to set app to immersive mode before it's ready and the flags do not stick 50 | container.postDelayed({ 51 | container.systemUiVisibility = FLAGS_FULLSCREEN 52 | }, IMMERSIVE_FLAG_TIMEOUT) 53 | } 54 | 55 | /** When key down event is triggered, relay it via local broadcast so fragments can handle it */ 56 | override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { 57 | return when (keyCode) { 58 | KeyEvent.KEYCODE_VOLUME_DOWN -> { 59 | val intent = Intent(KEY_EVENT_ACTION).apply { putExtra(KEY_EVENT_EXTRA, keyCode) } 60 | LocalBroadcastManager.getInstance(this).sendBroadcast(intent) 61 | true 62 | } 63 | else -> super.onKeyDown(keyCode, event) 64 | } 65 | } 66 | 67 | companion object { 68 | 69 | /** Use external media if it is available, our app's file directory otherwise */ 70 | fun getOutputDirectory(context: Context): File { 71 | val appContext = context.applicationContext 72 | val mediaDir = context.externalMediaDirs.firstOrNull()?.let { 73 | File(it, appContext.resources.getString(R.string.app_name)).apply { mkdirs() } } 74 | return if (mediaDir != null && mediaDir.exists()) 75 | mediaDir else appContext.filesDir 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/CameraFragment.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.example.cameraxbasic.fragments 18 | 19 | import android.annotation.SuppressLint 20 | import android.content.BroadcastReceiver 21 | import android.content.Context 22 | import android.content.Intent 23 | import android.content.IntentFilter 24 | import android.graphics.Color 25 | import android.graphics.drawable.BitmapDrawable 26 | import android.graphics.drawable.ColorDrawable 27 | import android.hardware.Camera 28 | import android.media.MediaScannerConnection 29 | import android.net.Uri 30 | import android.os.Build 31 | import android.os.Bundle 32 | import android.os.Handler 33 | import android.os.HandlerThread 34 | import android.util.DisplayMetrics 35 | import android.util.Log 36 | import android.util.Rational 37 | import android.util.Size 38 | import android.view.KeyEvent 39 | import android.view.LayoutInflater 40 | import android.view.TextureView 41 | import android.view.View 42 | import android.view.ViewGroup 43 | import android.webkit.MimeTypeMap 44 | import android.widget.ImageButton 45 | import androidx.camera.core.CameraX 46 | import androidx.camera.core.ImageAnalysis 47 | import androidx.camera.core.ImageAnalysisConfig 48 | import androidx.camera.core.ImageCapture 49 | import androidx.camera.core.ImageCaptureConfig 50 | import androidx.camera.core.ImageCapture.CaptureMode 51 | import androidx.camera.core.ImageCapture.Metadata 52 | import androidx.camera.core.ImageProxy 53 | import androidx.camera.core.PreviewConfig 54 | import androidx.navigation.Navigation 55 | import androidx.constraintlayout.widget.ConstraintLayout 56 | import androidx.fragment.app.Fragment 57 | import androidx.localbroadcastmanager.content.LocalBroadcastManager 58 | import com.android.example.cameraxbasic.KEY_EVENT_ACTION 59 | import com.android.example.cameraxbasic.KEY_EVENT_EXTRA 60 | import com.android.example.cameraxbasic.MainActivity 61 | import com.android.example.cameraxbasic.R 62 | import com.android.example.cameraxbasic.utils.ANIMATION_FAST_MILLIS 63 | import com.android.example.cameraxbasic.utils.ANIMATION_SLOW_MILLIS 64 | import com.android.example.cameraxbasic.utils.AutoFitPreviewBuilder 65 | import com.android.example.cameraxbasic.utils.ImageUtils 66 | import com.android.example.cameraxbasic.utils.simulateClick 67 | import com.bumptech.glide.Glide 68 | import kotlinx.coroutines.CoroutineScope 69 | import kotlinx.coroutines.Dispatchers 70 | import kotlinx.coroutines.Job 71 | import kotlinx.coroutines.launch 72 | import kotlinx.coroutines.withContext 73 | import java.io.File 74 | import java.lang.Exception 75 | import java.nio.ByteBuffer 76 | import java.text.SimpleDateFormat 77 | import java.util.ArrayDeque 78 | import java.util.Locale 79 | import java.util.concurrent.TimeUnit 80 | import kotlin.coroutines.CoroutineContext 81 | 82 | 83 | private const val TAG = "CameraXBasic" 84 | private const val FILENAME = "yyyy-MM-dd-HH-mm-ss-SSS" 85 | private const val PHOTO_EXTENSION = ".jpg" 86 | 87 | 88 | /** Helper function used to create a timestamped file */ 89 | private fun createFile(baseFolder: File, format: String, extension: String): File { 90 | return File(baseFolder, 91 | SimpleDateFormat(format, Locale.US).format(System.currentTimeMillis()) + extension) 92 | } 93 | 94 | /** 95 | * Main fragment for this app. Implements all camera operations including: 96 | * - Viewfinder 97 | * - Photo taking 98 | * - Image analysis 99 | */ 100 | class CameraFragment : Fragment(), CoroutineScope { 101 | 102 | private lateinit var container: ConstraintLayout 103 | private lateinit var viewFinder: TextureView 104 | private lateinit var outputDirectory: File 105 | 106 | private var lensFacing = CameraX.LensFacing.BACK 107 | private var imageCapture: ImageCapture? = null 108 | 109 | private val job = Job() 110 | override val coroutineContext: CoroutineContext 111 | get() = Dispatchers.Default + job 112 | 113 | // Volume down button receiver 114 | private val volumeDownReceiver = object : BroadcastReceiver() { 115 | override fun onReceive(context: Context, intent: Intent) { 116 | val keyCode = intent.getIntExtra(KEY_EVENT_EXTRA, KeyEvent.KEYCODE_UNKNOWN) 117 | when (keyCode) { 118 | // When the volume down button is pressed, simulate a shutter button click 119 | KeyEvent.KEYCODE_VOLUME_DOWN -> { 120 | val shutter = container 121 | .findViewById(R.id.camera_capture_button) 122 | shutter.simulateClick() 123 | } 124 | } 125 | } 126 | } 127 | 128 | override fun onCreate(savedInstanceState: Bundle?) { 129 | super.onCreate(savedInstanceState) 130 | // Mark this as a retain fragment, so the lifecycle does not get restarted on config change 131 | retainInstance = true 132 | } 133 | 134 | override fun onDestroyView() { 135 | super.onDestroyView() 136 | 137 | // Unregister the broadcast receivers 138 | LocalBroadcastManager.getInstance(requireContext()).unregisterReceiver(volumeDownReceiver) 139 | 140 | // Turn off all camera operations when we navigate away 141 | CameraX.unbindAll() 142 | } 143 | 144 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, 145 | savedInstanceState: Bundle?): View? { 146 | 147 | // Inflate the layout for this fragment 148 | return inflater.inflate(R.layout.fragment_camera, container, false) 149 | } 150 | 151 | override fun onDestroy() { 152 | // Stop the coroutines as the context gets destroyed 153 | job.cancel() 154 | super.onDestroy() 155 | } 156 | 157 | private fun setGalleryThumbnail(file: File) { 158 | // Reference of the view that holds the gallery thumbnail 159 | val thumbnail = container.findViewById(R.id.photo_view_button) 160 | 161 | // Use a coroutine to perform thumbnail operations in background 162 | launch(coroutineContext) { 163 | 164 | // Create thumbnail for this photo 165 | val bitmap = ImageUtils.decodeBitmap(file) 166 | 167 | // Crop the bitmap into a circle for the thumbnail 168 | val thumbnailBitmap = ImageUtils.cropCircularThumbnail(bitmap) 169 | 170 | // Set the foreground drawable if we can, fallback using Glide 171 | // This must be done in the main thread, so use main thread's context 172 | withContext(Dispatchers.Main) { 173 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 174 | thumbnail.foreground = BitmapDrawable(resources, thumbnailBitmap) 175 | } else { 176 | Glide.with(requireContext()).load(thumbnailBitmap).into(thumbnail) 177 | } 178 | } 179 | } 180 | } 181 | 182 | /** Define callback that will be triggered after a photo has been taken and saved to disk */ 183 | private val imageSavedListener = object : ImageCapture.OnImageSavedListener { 184 | override fun onError( 185 | error: ImageCapture.UseCaseError, message: String, exc: Throwable?) { 186 | Log.e(TAG, "Photo capture failed: $message") 187 | exc?.printStackTrace() 188 | } 189 | 190 | override fun onImageSaved(photoFile: File) { 191 | Log.d(TAG, "Photo capture succeeded: ${photoFile.absolutePath}") 192 | 193 | 194 | // We can only change the foreground Drawable using API level 23+ API 195 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 196 | 197 | // Update the gallery thumbnail with latest picture taken 198 | setGalleryThumbnail(photoFile) 199 | } 200 | 201 | // Implicit broadcasts will be ignored for devices running API 202 | // level >= 24, so if you only target 24+ you can remove this statement 203 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { 204 | requireActivity().sendBroadcast( 205 | Intent(Camera.ACTION_NEW_PICTURE).setData(Uri.fromFile(photoFile))) 206 | } 207 | 208 | // If the folder selected is an external media directory, this is unnecessary 209 | // but otherwise other apps will not be able to access our images unless we 210 | // scan them using [MediaScannerConnection] 211 | val mimeType = MimeTypeMap.getSingleton() 212 | .getMimeTypeFromExtension(photoFile.extension) 213 | MediaScannerConnection.scanFile( 214 | context, arrayOf(photoFile.absolutePath), arrayOf(mimeType), null) 215 | } 216 | } 217 | 218 | @SuppressLint("MissingPermission") 219 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 220 | super.onViewCreated(view, savedInstanceState) 221 | container = view as ConstraintLayout 222 | viewFinder = container.findViewById(R.id.view_finder) 223 | 224 | // Set up the intent filter that will receive events from our main activity 225 | val filter = IntentFilter().apply { addAction(KEY_EVENT_ACTION) } 226 | LocalBroadcastManager.getInstance(context!!).registerReceiver(volumeDownReceiver, filter) 227 | 228 | // Determine the output directory 229 | outputDirectory = MainActivity.getOutputDirectory(requireContext()) 230 | 231 | // Build UI and bind all camera use cases once the views have been laid out 232 | viewFinder.post { 233 | updateCameraUi() 234 | bindCameraUseCases() 235 | 236 | // In the background, load latest photo taken (if any) for gallery thumbnail 237 | launch(coroutineContext) { 238 | outputDirectory.listFiles { file -> 239 | EXTENSION_WHITELIST.contains(file.extension.toUpperCase()) 240 | }.sorted().reversed().firstOrNull()?.let { setGalleryThumbnail(it) } 241 | } 242 | } 243 | } 244 | 245 | /** Declare and bind preview, capture and analysis use cases */ 246 | private fun bindCameraUseCases() { 247 | 248 | // Make sure that there are no other use cases bound to CameraX 249 | CameraX.unbindAll() 250 | 251 | val metrics = DisplayMetrics().also { viewFinder.display.getRealMetrics(it) } 252 | val screenSize = Size(metrics.widthPixels, metrics.heightPixels) 253 | val screenAspectRatio = Rational(metrics.widthPixels, metrics.heightPixels) 254 | Log.d(javaClass.simpleName, "Metrics: ${metrics.widthPixels} x ${metrics.heightPixels}") 255 | 256 | // Set up the view finder use case to display camera preview 257 | val viewFinderConfig = PreviewConfig.Builder().apply { 258 | setLensFacing(lensFacing) 259 | // We request a specific resolution matching screen size 260 | setTargetResolution(screenSize) 261 | // We also provide an aspect ratio in case the exact resolution is not available 262 | setTargetAspectRatio(screenAspectRatio) 263 | setTargetRotation(viewFinder.display.rotation) 264 | }.build() 265 | 266 | // Use the auto-fit preview builder to automatically handle size and orientation changes 267 | val preview = AutoFitPreviewBuilder.build(viewFinderConfig, viewFinder) 268 | 269 | // Set up the capture use case to allow users to take photos 270 | val imageCaptureConfig = ImageCaptureConfig.Builder().apply { 271 | setLensFacing(lensFacing) 272 | setCaptureMode(CaptureMode.MIN_LATENCY) 273 | // We request aspect ratio but no resolution to match preview config but letting 274 | // CameraX optimize for whatever specific resolution best fits requested capture mode 275 | setTargetAspectRatio(screenAspectRatio) 276 | setTargetRotation(viewFinder.display.rotation) 277 | }.build() 278 | 279 | imageCapture = ImageCapture(imageCaptureConfig) 280 | 281 | // Setup image analysis pipeline that computes average pixel luminance in real time 282 | val analyzerConfig = ImageAnalysisConfig.Builder().apply { 283 | setLensFacing(lensFacing) 284 | // Use a worker thread for image analysis to prevent preview glitches 285 | val analyzerThread = HandlerThread("LuminosityAnalysis").apply { start() } 286 | setCallbackHandler(Handler(analyzerThread.looper)) 287 | // In our analysis, we care more about the latest image than analyzing *every* image 288 | setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE) 289 | }.build() 290 | 291 | val imageAnalyzer = ImageAnalysis(analyzerConfig).apply { 292 | analyzer = LuminosityAnalyzer().apply { onFrameAnalyzed { luma -> 293 | // Values returned from our analyzer are passed to the attached listener 294 | // We log image analysis results here -- you should do something 295 | // useful instead! 296 | Log.d(TAG, "Average luminosity: $luma. " + 297 | "Frames per second: ${"%.01f".format(framesPerSecond)}") } 298 | } } 299 | 300 | // Apply declared configs to CameraX using the same lifecycle owner 301 | CameraX.bindToLifecycle( 302 | this, preview, imageCapture, imageAnalyzer) 303 | } 304 | 305 | /** Method used to re-draw the camera UI controls, called every time configuration changes */ 306 | @SuppressLint("RestrictedApi") 307 | private fun updateCameraUi() { 308 | 309 | // Remove previous UI if any 310 | container.findViewById(R.id.camera_ui_container)?.let { 311 | container.removeView(it) 312 | } 313 | 314 | // Inflate a new view containing all UI for controlling the camera 315 | val controls = View.inflate(requireContext(), R.layout.camera_ui_container, container) 316 | 317 | // Listener for button used to capture photo 318 | controls.findViewById(R.id.camera_capture_button).setOnClickListener { 319 | val photoFile = createFile(outputDirectory, FILENAME, PHOTO_EXTENSION) 320 | 321 | // Setup image capture metadata 322 | val metadata = Metadata().apply { 323 | // Mirror image when using the front camera 324 | isReversedHorizontal = lensFacing == CameraX.LensFacing.FRONT 325 | } 326 | 327 | // Setup image capture listener which is triggered after photo has been taken 328 | imageCapture?.takePicture(photoFile, imageSavedListener, metadata) 329 | 330 | // We can only change the foreground Drawable using API level 23+ API 331 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 332 | 333 | // Display flash animation to indicate that photo was captured 334 | container.postDelayed({ 335 | container.foreground = ColorDrawable(Color.WHITE) 336 | container.postDelayed({ container.foreground = null }, ANIMATION_FAST_MILLIS) 337 | }, ANIMATION_SLOW_MILLIS) 338 | } 339 | } 340 | 341 | // Listener for button used to switch cameras 342 | controls.findViewById(R.id.camera_switch_button).setOnClickListener { 343 | lensFacing = if (CameraX.LensFacing.FRONT == lensFacing) { 344 | CameraX.LensFacing.BACK 345 | } else { 346 | CameraX.LensFacing.FRONT 347 | } 348 | try { 349 | // Only bind use cases if we can query a camera with this orientation 350 | CameraX.getCameraWithLensFacing(lensFacing) 351 | bindCameraUseCases() 352 | } catch (exc: Exception) { 353 | // Do nothing 354 | } 355 | } 356 | 357 | // Listener for button used to view last photo 358 | controls.findViewById(R.id.photo_view_button).setOnClickListener { 359 | val arguments = Bundle().apply { 360 | putString(KEY_ROOT_DIRECTORY, outputDirectory.absolutePath) } 361 | Navigation.findNavController(requireActivity(), R.id.fragment_container) 362 | .navigate(R.id.action_camera_to_gallery, arguments) 363 | } 364 | } 365 | 366 | 367 | /** 368 | * Our custom image analysis class. 369 | * 370 | *

All we need to do is override the function `analyze` with our desired operations. Here, 371 | * we compute the average luminosity of the image by looking at the Y plane of the YUV frame. 372 | */ 373 | private class LuminosityAnalyzer : ImageAnalysis.Analyzer { 374 | private val frameRateWindow = 8 375 | private val frameTimestamps = ArrayDeque(5) 376 | private val listeners = ArrayList<(luma: Double) -> Unit>() 377 | private var lastAnalyzedTimestamp = 0L 378 | var framesPerSecond: Double = -1.0 379 | private set 380 | 381 | /** 382 | * Used to add listeners that will be called with each luma computed 383 | */ 384 | fun onFrameAnalyzed(listener: (luma: Double) -> Unit) = listeners.add(listener) 385 | 386 | /** 387 | * Helper extension function used to extract a byte array from an image plane buffer 388 | */ 389 | private fun ByteBuffer.toByteArray(): ByteArray { 390 | rewind() // Rewind the buffer to zero 391 | val data = ByteArray(remaining()) 392 | get(data) // Copy the buffer into a byte array 393 | return data // Return the byte array 394 | } 395 | 396 | /** 397 | * Analyzes an image to produce a result. 398 | * 399 | *

The caller is responsible for ensuring this analysis method can be executed quickly 400 | * enough to prevent stalls in the image acquisition pipeline. Otherwise, newly available 401 | * images will not be acquired and analyzed. 402 | * 403 | *

The image passed to this method becomes invalid after this method returns. The caller 404 | * should not store external references to this image, as these references will become 405 | * invalid. 406 | * 407 | * @param image image being analyzed VERY IMPORTANT: do not close the image, it will be 408 | * automatically closed after this method returns 409 | * @return the image analysis result 410 | */ 411 | override fun analyze(image: ImageProxy, rotationDegrees: Int) { 412 | // If there are no listeners attached, we don't need to perform analysis 413 | if (listeners.isEmpty()) return 414 | 415 | // Keep track of frames analyzed 416 | frameTimestamps.push(System.currentTimeMillis()) 417 | 418 | // Compute the FPS using a moving average 419 | while (frameTimestamps.size >= frameRateWindow) frameTimestamps.removeLast() 420 | framesPerSecond = 1.0 / ((frameTimestamps.peekFirst() - 421 | frameTimestamps.peekLast()) / frameTimestamps.size.toDouble()) * 1000.0 422 | 423 | // Calculate the average luma no more often than every second 424 | if (frameTimestamps.first - lastAnalyzedTimestamp >= TimeUnit.SECONDS.toMillis(1)) { 425 | // Since format in ImageAnalysis is YUV, image.planes[0] contains the Y 426 | // (luminance) plane 427 | val buffer = image.planes[0].buffer 428 | 429 | // Extract image data from callback object 430 | val data = buffer.toByteArray() 431 | 432 | // Convert the data into an array of pixel values 433 | val pixels = data.map { it.toInt() and 0xFF } 434 | 435 | // Compute average luminance for the image 436 | val luma = pixels.average() 437 | 438 | // Call all listeners with new value 439 | listeners.forEach { it(luma) } 440 | 441 | lastAnalyzedTimestamp = frameTimestamps.first 442 | } 443 | } 444 | } 445 | } 446 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/GalleryFragment.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.example.cameraxbasic.fragments 18 | 19 | import android.os.Bundle 20 | import android.view.LayoutInflater 21 | import android.view.View 22 | import android.view.ViewGroup 23 | import android.widget.ImageButton 24 | import androidx.fragment.app.Fragment 25 | import androidx.fragment.app.FragmentManager 26 | import androidx.fragment.app.FragmentStatePagerAdapter 27 | import androidx.viewpager.widget.ViewPager 28 | import java.io.File 29 | import android.content.Intent 30 | import android.os.Build 31 | import android.webkit.MimeTypeMap 32 | import androidx.constraintlayout.widget.ConstraintLayout 33 | import androidx.core.content.FileProvider 34 | import com.android.example.cameraxbasic.BuildConfig 35 | import com.android.example.cameraxbasic.utils.padWithDisplayCutout 36 | import androidx.appcompat.app.AlertDialog 37 | import com.android.example.cameraxbasic.utils.showImmersive 38 | import com.android.example.cameraxbasic.R 39 | 40 | 41 | const val KEY_ROOT_DIRECTORY = "root_folder" 42 | val EXTENSION_WHITELIST = arrayOf("JPG") 43 | 44 | /** Fragment used to present the user with a gallery of photos taken */ 45 | class GalleryFragment internal constructor() : Fragment() { 46 | private lateinit var rootDirectory: File 47 | private lateinit var mediaList: MutableList 48 | private lateinit var mediaViewPager: ViewPager 49 | 50 | /** Adapter class used to present a fragment containing one photo or video as a page */ 51 | inner class MediaPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) { 52 | override fun getCount(): Int = mediaList.size 53 | override fun getItem(position: Int): Fragment = PhotoFragment.create(mediaList[position]) 54 | override fun getItemPosition(obj: Any): Int = POSITION_NONE 55 | } 56 | 57 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, 58 | savedInstanceState: Bundle?): View? { 59 | // Inflate the layout for this fragment 60 | return inflater.inflate(R.layout.fragment_gallery, container, false) 61 | } 62 | 63 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 64 | super.onViewCreated(view, savedInstanceState) 65 | 66 | // Mark this as a retain fragment, so the lifecycle does not get restarted on config change 67 | retainInstance = true 68 | 69 | arguments?.let { 70 | rootDirectory = File(it.getString(KEY_ROOT_DIRECTORY)) 71 | 72 | // Walk through all files in the root directory 73 | // We reverse the order of the list to present the last photos first 74 | mediaList = rootDirectory.listFiles { file -> 75 | EXTENSION_WHITELIST.contains(file.extension.toUpperCase()) 76 | }.sorted().reversed().toMutableList() 77 | 78 | // Populate the ViewPager and implement a cache of two media items 79 | mediaViewPager = view.findViewById(R.id.photo_view_pager).apply { 80 | offscreenPageLimit = 2 81 | adapter = MediaPagerAdapter(childFragmentManager) 82 | } 83 | } 84 | 85 | // Make sure that the cutout "safe area" avoids the screen notch if any 86 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { 87 | // Use extension method to pad "inside" view containing UI using display cutout's bounds 88 | view.findViewById(R.id.cutout_safe_area).padWithDisplayCutout() 89 | } 90 | 91 | // Handle back button press 92 | view.findViewById(R.id.back_button).setOnClickListener { 93 | fragmentManager?.popBackStack() 94 | } 95 | 96 | // Handle share button press 97 | view.findViewById(R.id.share_button).setOnClickListener { 98 | // Make sure that we have a file to share 99 | mediaList.getOrNull(mediaViewPager.currentItem)?.let { mediaFile -> 100 | val appContext = requireContext().applicationContext 101 | 102 | // Create a sharing intent 103 | val intent = Intent().apply { 104 | // Infer media type from file extension 105 | val mediaType = MimeTypeMap.getSingleton() 106 | .getMimeTypeFromExtension(mediaFile.extension) 107 | // Get URI from our FileProvider implementation 108 | val uri = FileProvider.getUriForFile( 109 | appContext, BuildConfig.APPLICATION_ID + ".provider", mediaFile) 110 | // Set the appropriate intent extra, type, action and flags 111 | putExtra(Intent.EXTRA_STREAM, uri) 112 | type = mediaType 113 | action = Intent.ACTION_SEND 114 | flags = Intent.FLAG_GRANT_READ_URI_PERMISSION 115 | } 116 | 117 | // Launch the intent letting the user choose which app to share with 118 | startActivity(Intent.createChooser(intent, getString(R.string.share_hint))) 119 | } 120 | } 121 | 122 | // Handle delete button press 123 | view.findViewById(R.id.delete_button).setOnClickListener { 124 | val context = requireContext() 125 | AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog) 126 | .setTitle(getString(R.string.delete_title)) 127 | .setMessage(getString(R.string.delete_dialog)) 128 | .setIcon(android.R.drawable.ic_dialog_alert) 129 | .setPositiveButton(android.R.string.yes) { _, _ -> 130 | mediaList.getOrNull(mediaViewPager.currentItem)?.let { mediaFile -> 131 | 132 | // Delete current photo 133 | mediaFile.delete() 134 | 135 | // Notify our view pager 136 | mediaList.removeAt(mediaViewPager.currentItem) 137 | mediaViewPager.adapter?.notifyDataSetChanged() 138 | 139 | // If all photos have been deleted, return to camera 140 | if (mediaList.isEmpty()) { 141 | fragmentManager?.popBackStack() 142 | } 143 | }} 144 | 145 | .setNegativeButton(android.R.string.no, null) 146 | .create().showImmersive() 147 | } 148 | } 149 | } -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/PermissionsFragment.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.example.cameraxbasic.fragments 18 | 19 | import android.Manifest 20 | import android.content.pm.PackageManager 21 | import android.os.Bundle 22 | import android.widget.Toast 23 | import androidx.core.content.ContextCompat 24 | import androidx.fragment.app.Fragment 25 | import androidx.navigation.NavOptions 26 | import androidx.navigation.Navigation 27 | import com.android.example.cameraxbasic.R 28 | 29 | private const val PERMISSIONS_REQUEST_CODE = 10 30 | private val PERMISSIONS_REQUIRED = arrayOf( 31 | Manifest.permission.CAMERA, 32 | Manifest.permission.RECORD_AUDIO) 33 | 34 | /** 35 | * The sole purpose of this fragment is to request permissions and, once granted, display the 36 | * camera fragment to the user. 37 | */ 38 | class PermissionsFragment : Fragment() { 39 | val navOptions = NavOptions.Builder().setPopUpTo(R.id.permissionsFragment, true).build() 40 | 41 | override fun onCreate(savedInstanceState: Bundle?) { 42 | super.onCreate(savedInstanceState) 43 | 44 | if (!hasPermissions()) { 45 | // Request camera-related permissions 46 | requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE) 47 | } else { 48 | // If permissions have already been granted, proceed 49 | Navigation.findNavController(requireActivity(), R.id.fragment_container) 50 | .navigate(R.id.action_permissions_to_camera, null, 51 | navOptions) 52 | } 53 | 54 | } 55 | 56 | private fun hasPermissions(): Boolean { 57 | for (permission in PERMISSIONS_REQUIRED) { 58 | if (ContextCompat.checkSelfPermission(requireContext(), permission) != 59 | PackageManager.PERMISSION_GRANTED) { 60 | return false 61 | } 62 | } 63 | return true 64 | } 65 | 66 | override fun onRequestPermissionsResult( 67 | requestCode: Int, permissions: Array, grantResults: IntArray) { 68 | super.onRequestPermissionsResult(requestCode, permissions, grantResults) 69 | if (requestCode == PERMISSIONS_REQUEST_CODE) { 70 | if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { 71 | // Take the user to the success fragment when permission is granted 72 | Toast.makeText(context, "Permission request granted", Toast.LENGTH_LONG).show() 73 | Navigation.findNavController(requireActivity(), R.id.fragment_container) 74 | .navigate(R.id.action_permissions_to_camera, null, 75 | navOptions) 76 | } else { 77 | Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show() 78 | } 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/PhotoFragment.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.example.cameraxbasic.fragments 18 | 19 | import android.os.Bundle 20 | import android.view.LayoutInflater 21 | import android.view.View 22 | import android.view.ViewGroup 23 | import android.widget.ImageView 24 | import androidx.fragment.app.Fragment 25 | import com.bumptech.glide.Glide 26 | import java.io.File 27 | 28 | private const val FILE_NAME_KEY = "file_name" 29 | 30 | /** Fragment used for each individual page showing a photo inside of [GalleryFragment] */ 31 | class PhotoFragment internal constructor() : Fragment() { 32 | 33 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, 34 | savedInstanceState: Bundle?) = ImageView(context) 35 | 36 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 37 | super.onViewCreated(view, savedInstanceState) 38 | arguments?.let { 39 | val file = File(it.getString(FILE_NAME_KEY)) 40 | Glide.with(this).load(file).into(view as ImageView) 41 | } 42 | } 43 | 44 | companion object { 45 | fun create(image: File) = PhotoFragment().apply { 46 | arguments = Bundle().apply { 47 | putString(FILE_NAME_KEY, image.absolutePath) 48 | } 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/Renderer.kt: -------------------------------------------------------------------------------- 1 | package com.android.example.cameraxbasic.fragments 2 | 3 | import android.graphics.SurfaceTexture 4 | import android.opengl.EGL14 5 | import android.opengl.GLES20 6 | import android.os.Handler 7 | import android.os.HandlerThread 8 | import android.os.Message 9 | import android.view.TextureView 10 | import java.nio.FloatBuffer 11 | import javax.microedition.khronos.egl.EGL10 12 | import javax.microedition.khronos.egl.EGLConfig 13 | import javax.microedition.khronos.egl.EGLContext 14 | import javax.microedition.khronos.egl.EGLSurface 15 | 16 | 17 | class Renderer : SurfaceTexture.OnFrameAvailableListener { 18 | private var mHandlerThread: HandlerThread? = null 19 | private var mHandler: Handler? = null 20 | private var mTextureView: TextureView? = null 21 | private var mOESTextureId: Int = 0 22 | private var mFilterEngine: TextureDrawer? = null 23 | private var mDataBuffer: FloatBuffer? = null 24 | private var mShaderProgram = -1 25 | private val transformMatrix = FloatArray(16) 26 | 27 | private var mEgl: EGL10? = null 28 | private var mEGLDisplay = EGL10.EGL_NO_DISPLAY 29 | private var mEGLContext = EGL10.EGL_NO_CONTEXT 30 | private val mEGLConfig = arrayOfNulls(1) 31 | private var mEglSurface: EGLSurface? = null 32 | private var mOESSurfaceTexture: SurfaceTexture? = null 33 | 34 | fun init(textureView: TextureView, oesTextureId: Int) { 35 | mTextureView = textureView 36 | mOESTextureId = oesTextureId 37 | mHandlerThread = HandlerThread("Renderer Thread") 38 | mHandlerThread!!.start() 39 | mHandler = object : Handler(mHandlerThread!!.looper) { 40 | override fun handleMessage(msg: Message) { 41 | when (msg.what) { 42 | MSG_INIT -> { 43 | initEGL() 44 | return 45 | } 46 | MSG_RENDER -> { 47 | drawFrame() 48 | return 49 | } 50 | MSG_INIT_SURFACE -> { 51 | initSurfaceTexture() 52 | return 53 | } 54 | MSG_DEINIT -> { 55 | deInitSurfaceTexture() 56 | } 57 | else -> return 58 | } 59 | } 60 | } 61 | mHandler!!.sendEmptyMessage(MSG_INIT) 62 | } 63 | 64 | private fun deInitSurfaceTexture() { 65 | mOESSurfaceTexture?.detachFromGLContext() 66 | } 67 | 68 | private fun initSurfaceTexture() { 69 | mOESSurfaceTexture!!.attachToGLContext(mOESTextureId) 70 | mOESSurfaceTexture!!.setOnFrameAvailableListener(this) 71 | } 72 | 73 | 74 | private fun initEGL() { 75 | mEgl = EGLContext.getEGL() as EGL10 76 | 77 | //获取显示设备 78 | mEGLDisplay = mEgl!!.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY) 79 | if (mEGLDisplay === EGL10.EGL_NO_DISPLAY) { 80 | throw RuntimeException("eglGetDisplay failed! " + mEgl!!.eglGetError()) 81 | } 82 | 83 | //version中存放EGL版本号 84 | val version = IntArray(2) 85 | 86 | //初始化EGL 87 | if (!mEgl!!.eglInitialize(mEGLDisplay, version)) { 88 | throw RuntimeException("eglInitialize failed! " + mEgl!!.eglGetError()) 89 | } 90 | 91 | //构造需要的配置列表 92 | val attributes = intArrayOf(EGL10.EGL_RED_SIZE, 8, EGL10.EGL_GREEN_SIZE, 8, EGL10.EGL_BLUE_SIZE, 8, EGL10.EGL_ALPHA_SIZE, 8, EGL10.EGL_BUFFER_SIZE, 32, EGL10.EGL_RENDERABLE_TYPE, 4, EGL10.EGL_SURFACE_TYPE, EGL10.EGL_WINDOW_BIT, EGL10.EGL_NONE) 93 | val configsNum = IntArray(1) 94 | 95 | //EGL选择配置 96 | if (!mEgl!!.eglChooseConfig(mEGLDisplay, attributes, mEGLConfig, 1, configsNum)) { 97 | throw RuntimeException("eglChooseConfig failed! " + mEgl!!.eglGetError()) 98 | } 99 | val surfaceTexture = mTextureView!!.surfaceTexture ?: return 100 | 101 | //创建EGL显示窗口 102 | mEglSurface = mEgl!!.eglCreateWindowSurface(mEGLDisplay, mEGLConfig[0], surfaceTexture, null) 103 | 104 | //创建上下文 105 | val contextAttribs = intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL10.EGL_NONE) 106 | mEGLContext = mEgl!!.eglCreateContext(mEGLDisplay, mEGLConfig[0], EGL10.EGL_NO_CONTEXT, contextAttribs) 107 | 108 | if (mEGLDisplay === EGL10.EGL_NO_DISPLAY || mEGLContext === EGL10.EGL_NO_CONTEXT) { 109 | throw RuntimeException("eglCreateContext fail failed! " + mEgl!!.eglGetError()) 110 | } 111 | 112 | if (!mEgl!!.eglMakeCurrent(mEGLDisplay, mEglSurface, mEglSurface, mEGLContext)) { 113 | throw RuntimeException("eglMakeCurrent failed! " + mEgl!!.eglGetError()) 114 | } 115 | 116 | mFilterEngine = TextureDrawer(mOESTextureId) 117 | mDataBuffer = mFilterEngine!!.buffer 118 | mShaderProgram = mFilterEngine!!.shaderProgram 119 | } 120 | 121 | private fun drawFrame() { 122 | if (mOESSurfaceTexture != null) { 123 | mOESSurfaceTexture!!.updateTexImage() 124 | mOESSurfaceTexture!!.getTransformMatrix(transformMatrix) 125 | } 126 | mEgl!!.eglMakeCurrent(mEGLDisplay, mEglSurface, mEglSurface, mEGLContext) 127 | GLES20.glViewport(0, 0, mTextureView!!.width, mTextureView!!.height) 128 | GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) 129 | GLES20.glClearColor(1f, 1f, 0f, 0f) 130 | mFilterEngine!!.drawTexture(transformMatrix) 131 | mEgl!!.eglSwapBuffers(mEGLDisplay, mEglSurface) 132 | } 133 | 134 | override fun onFrameAvailable(surfaceTexture: SurfaceTexture) { 135 | if (mHandler != null) { 136 | mHandler!!.sendEmptyMessage(MSG_RENDER) 137 | } 138 | } 139 | 140 | fun initOESTexture(st: SurfaceTexture) { 141 | mOESSurfaceTexture = st 142 | 143 | if (mHandler != null) { 144 | mHandler!!.sendEmptyMessage(MSG_INIT_SURFACE) 145 | } 146 | } 147 | 148 | companion object { 149 | private val MSG_INIT = 1 150 | private val MSG_RENDER = 2 151 | private val MSG_DEINIT = 3 152 | private val MSG_INIT_SURFACE = 4 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/TextureDrawer.kt: -------------------------------------------------------------------------------- 1 | package com.android.example.cameraxbasic.fragments 2 | 3 | import android.opengl.GLES11Ext 4 | import android.opengl.GLES20 5 | import android.opengl.GLES20.* 6 | import java.nio.ByteBuffer 7 | import java.nio.ByteOrder 8 | import java.nio.FloatBuffer 9 | import javax.microedition.khronos.opengles.GL10 10 | 11 | class TextureDrawer(OESTextureId: Int) { 12 | val buffer: FloatBuffer? 13 | private var mOESTextureId = -1 14 | private var vertexShader = -1 15 | private var fragmentShader = -1 16 | var shaderProgram = -1 17 | 18 | private var aPositionLocation = -1 19 | private var aTextureCoordLocation = -1 20 | private var uTextureMatrixLocation = -1 21 | private var uTextureSamplerLocation = -1 22 | 23 | init { 24 | mOESTextureId = OESTextureId 25 | buffer = createBuffer(vertexData) 26 | vertexShader = loadShader(GL_VERTEX_SHADER, VERTEX_SHADER) 27 | fragmentShader = loadShader(GL_FRAGMENT_SHADER, FRAGMENT_SHADER) 28 | shaderProgram = linkProgram(vertexShader, fragmentShader) 29 | } 30 | 31 | private fun createBuffer(vertexData: FloatArray): FloatBuffer { 32 | val buffer = ByteBuffer.allocateDirect(vertexData.size * 4) 33 | .order(ByteOrder.nativeOrder()) 34 | .asFloatBuffer() 35 | buffer.put(vertexData, 0, vertexData.size).position(0) 36 | return buffer 37 | } 38 | 39 | private fun loadShader(type: Int, shaderSource: String): Int { 40 | val shader = glCreateShader(type) 41 | if (shader == 0) { 42 | throw RuntimeException("Create Shader Failed!" + glGetError()) 43 | } 44 | glShaderSource(shader, shaderSource) 45 | glCompileShader(shader) 46 | return shader 47 | } 48 | 49 | private fun linkProgram(verShader: Int, fragShader: Int): Int { 50 | val program = glCreateProgram() 51 | if (program == 0) { 52 | throw RuntimeException("Create Program Failed!" + glGetError()) 53 | } 54 | glAttachShader(program, verShader) 55 | glAttachShader(program, fragShader) 56 | glLinkProgram(program) 57 | 58 | glUseProgram(program) 59 | return program 60 | } 61 | 62 | fun drawTexture(transformMatrix: FloatArray) { 63 | aPositionLocation = glGetAttribLocation(shaderProgram, TextureDrawer.POSITION_ATTRIBUTE) 64 | aTextureCoordLocation = glGetAttribLocation(shaderProgram, TextureDrawer.TEXTURE_COORD_ATTRIBUTE) 65 | uTextureMatrixLocation = glGetUniformLocation(shaderProgram, TextureDrawer.TEXTURE_MATRIX_UNIFORM) 66 | uTextureSamplerLocation = glGetUniformLocation(shaderProgram, TextureDrawer.TEXTURE_SAMPLER_UNIFORM) 67 | 68 | glActiveTexture(GLES20.GL_TEXTURE0) 69 | glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mOESTextureId) 70 | glUniform1i(uTextureSamplerLocation, 0) 71 | glUniformMatrix4fv(uTextureMatrixLocation, 1, false, transformMatrix, 0) 72 | 73 | if (buffer != null) { 74 | buffer.position(0) 75 | glEnableVertexAttribArray(aPositionLocation) 76 | glVertexAttribPointer(aPositionLocation, 2, GL_FLOAT, false, 16, buffer) 77 | 78 | buffer.position(2) 79 | glEnableVertexAttribArray(aTextureCoordLocation) 80 | glVertexAttribPointer(aTextureCoordLocation, 2, GL_FLOAT, false, 16, buffer) 81 | 82 | glDrawArrays(GL_TRIANGLES, 0, 6) 83 | } 84 | } 85 | 86 | companion object { 87 | 88 | private val vertexData = floatArrayOf( 89 | 1f, 1f, 1f, 1f, 90 | -1f, 1f, 0f, 1f, 91 | -1f, -1f, 0f, 0f, 92 | 1f, 1f, 1f, 1f, 93 | -1f, -1f, 0f, 0f, 94 | 1f, -1f, 1f, 0f) 95 | 96 | private val POSITION_ATTRIBUTE = "aPosition" 97 | private val TEXTURE_COORD_ATTRIBUTE = "aTextureCoordinate" 98 | private val TEXTURE_MATRIX_UNIFORM = "uTextureMatrix" 99 | private val TEXTURE_SAMPLER_UNIFORM = "uTextureSampler" 100 | 101 | private val VERTEX_SHADER = "attribute vec4 aPosition;\n" + 102 | "uniform mat4 uTextureMatrix;\n" + 103 | "attribute vec4 aTextureCoordinate;\n" + 104 | "varying vec2 vTextureCoord;\n" + 105 | "void main()\n" + 106 | "{\n" + 107 | " vTextureCoord = (uTextureMatrix * aTextureCoordinate).xy;\n" + 108 | " gl_Position = aPosition;\n" + 109 | "}" 110 | 111 | private val FRAGMENT_SHADER = "#extension GL_OES_EGL_image_external : require\n" + 112 | "precision mediump float;\n" + 113 | "uniform samplerExternalOES uTextureSampler;\n" + 114 | "varying vec2 vTextureCoord;\n" + 115 | "void main()\n" + 116 | "{\n" + 117 | " vec4 vCameraColor = texture2D(uTextureSampler, vTextureCoord);\n" + 118 | " float fGrayColor = (0.3*vCameraColor.r + 0.59*vCameraColor.g + 0.11*vCameraColor.b);\n" + 119 | " gl_FragColor = vec4(fGrayColor, fGrayColor, fGrayColor, 1.0);\n" + 120 | "}\n" 121 | 122 | 123 | fun createOESTextureObject(): Int { 124 | val tex = IntArray(1) 125 | GLES20.glGenTextures(1, tex, 0) 126 | GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, tex[0]) 127 | GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 128 | GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST.toFloat()) 129 | GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 130 | GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR.toFloat()) 131 | GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 132 | GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE.toFloat()) 133 | GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 134 | GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE.toFloat()) 135 | GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0) 136 | return tex[0] 137 | } 138 | } 139 | } 140 | 141 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/utils/AutoFitPreviewBuilder.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.example.cameraxbasic.utils 18 | 19 | import android.content.Context 20 | import android.graphics.Matrix 21 | import android.graphics.SurfaceTexture 22 | import android.hardware.display.DisplayManager 23 | import android.util.Log 24 | import android.util.Size 25 | import android.view.* 26 | import androidx.camera.core.Preview 27 | import androidx.camera.core.PreviewConfig 28 | import com.android.example.cameraxbasic.fragments.Renderer 29 | import com.android.example.cameraxbasic.fragments.TextureDrawer 30 | import java.lang.IllegalArgumentException 31 | import java.lang.ref.WeakReference 32 | import java.util.Objects 33 | 34 | /** 35 | * Builder for [Preview] that takes in a [WeakReference] of the view finder and 36 | * [PreviewConfig], then instantiates a [Preview] which automatically 37 | * resizes and rotates reacting to config changes. 38 | */ 39 | class AutoFitPreviewBuilder private constructor(config: PreviewConfig, 40 | viewFinderRef: WeakReference) { 41 | /** Public instance of preview use-case which can be used by consumers of this adapter */ 42 | val useCase: Preview 43 | 44 | /** Internal variable used to keep track of the use-case's output rotation */ 45 | private var bufferRotation: Int = 0 46 | /** Internal variable used to keep track of the view's rotation */ 47 | private var viewFinderRotation: Int? = null 48 | /** Internal variable used to keep track of the use-case's output dimension */ 49 | private var bufferDimens: Size = Size(0, 0) 50 | /** Internal variable used to keep track of the view's dimension */ 51 | private var viewFinderDimens: Size = Size(0, 0) 52 | /** Internal variable used to keep track of the view's display */ 53 | private var viewFinderDisplay: Int = -1 54 | 55 | private lateinit var displayManager: DisplayManager 56 | /** We need a display listener for 180 degree device orientation changes */ 57 | private val displayListener = object : DisplayManager.DisplayListener { 58 | override fun onDisplayAdded(displayId: Int) = Unit 59 | override fun onDisplayRemoved(displayId: Int) = Unit 60 | override fun onDisplayChanged(displayId: Int) { 61 | val viewFinder = viewFinderRef.get() ?: return 62 | if (displayId != viewFinderDisplay) { 63 | val display = displayManager.getDisplay(displayId) 64 | val rotation = getDisplaySurfaceRotation(display) 65 | updateTransform(viewFinder, rotation, bufferDimens, viewFinderDimens) 66 | } 67 | } 68 | } 69 | 70 | private var mOESTextureId = -1 71 | private var mRenderer: Renderer = Renderer() 72 | 73 | init { 74 | // Make sure that the view finder reference is valid 75 | val viewFinder = viewFinderRef.get() ?: throw IllegalArgumentException( 76 | "Invalid reference to view finder used") 77 | 78 | // Initialize the display and rotation from texture view information 79 | viewFinderDisplay = viewFinder.display.displayId 80 | viewFinderRotation = getDisplaySurfaceRotation(viewFinder.display) ?: 0 81 | 82 | // Initialize public use-case with the given config 83 | useCase = Preview(config) 84 | 85 | 86 | // Every time the view finder is updated, recompute layout 87 | useCase.onPreviewOutputUpdateListener = Preview.OnPreviewOutputUpdateListener { 88 | val viewFinder = 89 | viewFinderRef.get() ?: return@OnPreviewOutputUpdateListener 90 | 91 | // To update the SurfaceTexture, we have to remove it and re-add it 92 | val parent = viewFinder.parent as ViewGroup 93 | parent.removeView(viewFinder) 94 | parent.addView(viewFinder, 0) 95 | 96 | Log.d("zhy", "OnPreviewOutputUpdateListener") 97 | 98 | // 启用下面的代码正常显示内容 99 | // viewFinder.surfaceTexture = it.surfaceTexture 100 | 101 | // 启用下面的代码,走 GL 线程,图像经过黑白滤镜处理 102 | viewFinder.surfaceTextureListener = object : TextureView.SurfaceTextureListener { 103 | 104 | override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture?, width: Int, height: Int) { 105 | } 106 | 107 | override fun onSurfaceTextureUpdated(surface: SurfaceTexture?) { 108 | } 109 | 110 | override fun onSurfaceTextureDestroyed(surface: SurfaceTexture?): Boolean { 111 | return true 112 | } 113 | 114 | override fun onSurfaceTextureAvailable(surface: SurfaceTexture?, width: Int, height: Int) { 115 | mOESTextureId = TextureDrawer.createOESTextureObject() 116 | mRenderer.init(viewFinder, mOESTextureId) 117 | mRenderer.initOESTexture(it.surfaceTexture) 118 | } 119 | } 120 | 121 | bufferRotation = it.rotationDegrees 122 | val rotation = getDisplaySurfaceRotation(viewFinder.display) 123 | updateTransform(viewFinder, rotation, it.textureSize, viewFinderDimens) 124 | } 125 | 126 | // Every time the provided texture view changes, recompute layout 127 | viewFinder.addOnLayoutChangeListener { view, left, top, right, bottom, _, _, _, _ -> 128 | val viewFinder = view as TextureView 129 | val newViewFinderDimens = Size(right - left, bottom - top) 130 | val rotation = getDisplaySurfaceRotation(viewFinder.display) 131 | updateTransform(viewFinder, rotation, bufferDimens, newViewFinderDimens) 132 | } 133 | 134 | // Every time the orientation of device changes, recompute layout 135 | displayManager = viewFinder.context 136 | .getSystemService(Context.DISPLAY_SERVICE) as DisplayManager 137 | displayManager.registerDisplayListener(displayListener, null) 138 | 139 | // Remove the display listeners when the view is detached to avoid 140 | // holding a reference to the View outside of a Fragment. 141 | // NOTE: Even though using a weak reference should take care of this, 142 | // we still try to avoid unnecessary calls to the listener this way. 143 | viewFinder.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { 144 | override fun onViewAttachedToWindow(view: View?) = Unit 145 | override fun onViewDetachedFromWindow(view: View?) { 146 | displayManager.unregisterDisplayListener(displayListener) 147 | } 148 | 149 | }) 150 | } 151 | 152 | /** Helper function that fits a camera preview into the given [TextureView] */ 153 | private fun updateTransform(textureView: TextureView?, rotation: Int?, newBufferDimens: Size, 154 | newViewFinderDimens: Size) { 155 | // This should happen anyway, but now the linter knows 156 | val textureView = textureView ?: return 157 | 158 | if (rotation == viewFinderRotation && 159 | Objects.equals(newBufferDimens, bufferDimens) && 160 | Objects.equals(newViewFinderDimens, viewFinderDimens)) { 161 | // Nothing has changed, no need to transform output again 162 | return 163 | } 164 | 165 | if (rotation == null) { 166 | // Invalid rotation - wait for valid inputs before setting matrix 167 | return 168 | } else { 169 | // Update internal field with new inputs 170 | viewFinderRotation = rotation 171 | } 172 | 173 | if (newBufferDimens.width == 0 || newBufferDimens.height == 0) { 174 | // Invalid buffer dimens - wait for valid inputs before setting matrix 175 | return 176 | } else { 177 | // Update internal field with new inputs 178 | bufferDimens = newBufferDimens 179 | } 180 | 181 | if (newViewFinderDimens.width == 0 || newViewFinderDimens.height == 0) { 182 | // Invalid view finder dimens - wait for valid inputs before setting matrix 183 | return 184 | } else { 185 | // Update internal field with new inputs 186 | viewFinderDimens = newViewFinderDimens 187 | } 188 | 189 | val matrix = Matrix() 190 | 191 | // Compute the center of the view finder 192 | val centerX = viewFinderDimens.width / 2f 193 | val centerY = viewFinderDimens.height / 2f 194 | 195 | // Correct preview output to account for display rotation 196 | matrix.postRotate(-viewFinderRotation!!.toFloat(), centerX, centerY) 197 | 198 | // Buffers are rotated relative to the device's 'natural' orientation: swap width and height 199 | val bufferRatio = bufferDimens.height / bufferDimens.width.toFloat() 200 | 201 | val scaledWidth: Int 202 | val scaledHeight: Int 203 | // Match longest sides together -- i.e. apply center-crop transformation 204 | if (viewFinderDimens.width > viewFinderDimens.height) { 205 | scaledHeight = viewFinderDimens.width 206 | scaledWidth = Math.round(viewFinderDimens.width * bufferRatio) 207 | } else { 208 | scaledHeight = viewFinderDimens.height 209 | scaledWidth = Math.round(viewFinderDimens.height * bufferRatio) 210 | } 211 | 212 | // Compute the relative scale value 213 | val xScale = scaledWidth / viewFinderDimens.width.toFloat() 214 | val yScale = scaledHeight / viewFinderDimens.height.toFloat() 215 | 216 | // Scale input buffers to fill the view finder 217 | matrix.preScale(xScale, yScale, centerX, centerY) 218 | 219 | // Finally, apply transformations to our TextureView 220 | textureView.setTransform(matrix) 221 | } 222 | 223 | companion object { 224 | /** Helper function that gets the rotation of a [Display] in degrees */ 225 | fun getDisplaySurfaceRotation(display: Display?) = when (display?.rotation) { 226 | Surface.ROTATION_0 -> 0 227 | Surface.ROTATION_90 -> 90 228 | Surface.ROTATION_180 -> 180 229 | Surface.ROTATION_270 -> 270 230 | else -> null 231 | } 232 | 233 | /** 234 | * Main entrypoint for users of this class: instantiates the adapter and returns an instance 235 | * of [Preview] which automatically adjusts in size and rotation to compensate for 236 | * config changes. 237 | */ 238 | fun build(config: PreviewConfig, viewFinder: TextureView) = 239 | AutoFitPreviewBuilder(config, WeakReference(viewFinder)).useCase 240 | } 241 | } -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/utils/ImageUtils.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.example.cameraxbasic.utils 18 | 19 | import android.graphics.Bitmap 20 | import android.graphics.BitmapFactory 21 | import android.graphics.Canvas 22 | import android.graphics.Color 23 | import android.graphics.Matrix 24 | import android.graphics.Paint 25 | import android.graphics.PorterDuff 26 | import android.graphics.PorterDuffXfermode 27 | import android.graphics.Rect 28 | import android.media.ThumbnailUtils 29 | import androidx.camera.core.ImageProxy 30 | import androidx.exifinterface.media.ExifInterface 31 | import java.io.File 32 | 33 | /** 34 | * Collection of image reading and manipulation utilities in the form of static functions. 35 | */ 36 | abstract class ImageUtils { 37 | companion object { 38 | 39 | /** 40 | * Helper function used to convert an EXIF orientation enum into a transformation matrix 41 | * that can be applied to a bitmap. 42 | * 43 | * @param orientation - One of the constants from [ExifInterface] 44 | */ 45 | private fun decodeExifOrientation(orientation: Int): Matrix { 46 | val matrix = Matrix() 47 | 48 | // Apply transformation corresponding to declared EXIF orientation 49 | when (orientation) { 50 | ExifInterface.ORIENTATION_NORMAL -> Unit 51 | ExifInterface.ORIENTATION_UNDEFINED -> Unit 52 | ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90F) 53 | ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180F) 54 | ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270F) 55 | ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.postScale(-1F, 1F) 56 | ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.postScale(1F, -1F) 57 | ExifInterface.ORIENTATION_TRANSPOSE -> { 58 | matrix.postScale(-1F, 1F) 59 | matrix.postRotate(270F) 60 | } 61 | ExifInterface.ORIENTATION_TRANSVERSE -> { 62 | matrix.postScale(-1F, 1F) 63 | matrix.postRotate(90F) 64 | } 65 | 66 | // Error out if the EXIF orientation is invalid 67 | else -> throw IllegalArgumentException("Invalid orientation: $orientation") 68 | } 69 | 70 | // Return the resulting matrix 71 | return matrix 72 | } 73 | 74 | /** 75 | * Decode a bitmap from a file and apply the transformations described in its EXIF data 76 | * 77 | * @param file - The image file to be read using [BitmapFactory.decodeFile] 78 | */ 79 | fun decodeBitmap(file: File): Bitmap { 80 | // First, decode EXIF data and retrieve transformation matrix 81 | val exif = ExifInterface(file.absolutePath) 82 | val transformation = decodeExifOrientation(exif.getAttributeInt( 83 | ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_ROTATE_90)) 84 | 85 | // Read bitmap using factory methods, and transform it using EXIF data 86 | val bitmap = BitmapFactory.decodeFile(file.absolutePath) 87 | return Bitmap.createBitmap( 88 | BitmapFactory.decodeFile(file.absolutePath), 89 | 0, 0, bitmap.width, bitmap.height, transformation, true) 90 | } 91 | 92 | fun decodeBitmap(image: ImageProxy): Bitmap { 93 | val buffer = image.planes[0].buffer 94 | val bytes = ByteArray(buffer.capacity()).also { buffer.get(it) } 95 | return BitmapFactory.decodeByteArray(bytes, 0, bytes.size) 96 | } 97 | 98 | /** 99 | * This function cuts out a circular thumbnail from the provided bitmap. This is done by 100 | * first scaling the image down to a square with width of [diameter], and then marking all 101 | * pixels outside of the inner circle as transparent. 102 | * 103 | * @param bitmap - The [Bitmap] to be taken a thumbnail of 104 | * @param diameter - Size in pixels for the diameter of the resulting circle 105 | */ 106 | fun cropCircularThumbnail(bitmap: Bitmap, diameter: Int = 128): Bitmap { 107 | // Extract a much smaller bitmap to serve as thumbnail 108 | val thumbnail = ThumbnailUtils.extractThumbnail(bitmap, diameter, diameter) 109 | 110 | // Create an additional bitmap of same size as thumbnail to carve a circle out of 111 | val circular = Bitmap.createBitmap( 112 | diameter, diameter, Bitmap.Config.ARGB_8888) 113 | 114 | // Paint will be used as a mask to cut out the circle 115 | val paint = Paint().apply { 116 | color = Color.BLACK 117 | } 118 | 119 | Canvas(circular).apply { 120 | drawARGB(0, 0, 0, 0) 121 | drawCircle(diameter / 2F, diameter / 2F, diameter / 2F - 8, paint) 122 | paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN) 123 | val rect = Rect(0, 0, diameter, diameter) 124 | drawBitmap(thumbnail, rect, rect, paint) 125 | } 126 | 127 | return circular 128 | } 129 | } 130 | } -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/utils/ViewExtensions.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.example.cameraxbasic.utils 18 | 19 | import android.os.Build 20 | import android.view.DisplayCutout 21 | import android.view.View 22 | import android.view.WindowManager 23 | import android.widget.ImageButton 24 | import androidx.annotation.RequiresApi 25 | import androidx.appcompat.app.AlertDialog 26 | 27 | /** Combination of all flags required to put activity into immersive mode */ 28 | const val FLAGS_FULLSCREEN = 29 | View.SYSTEM_UI_FLAG_LOW_PROFILE or 30 | View.SYSTEM_UI_FLAG_FULLSCREEN or 31 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE or 32 | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or 33 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or 34 | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION 35 | 36 | /** Milliseconds used for UI animations */ 37 | const val ANIMATION_FAST_MILLIS = 50L 38 | const val ANIMATION_SLOW_MILLIS = 100L 39 | 40 | /** 41 | * Simulate a button click, including a small delay while it is being pressed to trigger the 42 | * appropriate animations. 43 | */ 44 | fun ImageButton.simulateClick(delay: Long = ANIMATION_FAST_MILLIS) { 45 | performClick() 46 | isPressed = true 47 | invalidate() 48 | postDelayed({ 49 | invalidate() 50 | isPressed = false 51 | }, delay) 52 | } 53 | 54 | /** Pad this view with the insets provided by the device cutout (i.e. notch) */ 55 | @RequiresApi(Build.VERSION_CODES.P) 56 | fun View.padWithDisplayCutout() { 57 | 58 | /** Helper method that applies padding from cutout's safe insets */ 59 | fun doPadding(cutout: DisplayCutout) = setPadding( 60 | cutout.safeInsetLeft, 61 | cutout.safeInsetTop, 62 | cutout.safeInsetRight, 63 | cutout.safeInsetBottom) 64 | 65 | // Apply padding using the display cutout designated "safe area" 66 | rootWindowInsets?.displayCutout?.let { doPadding(it) } 67 | 68 | // Set a listener for window insets since view.rootWindowInsets may not be ready yet 69 | setOnApplyWindowInsetsListener { view, insets -> 70 | insets.displayCutout?.let { doPadding(it) } 71 | insets 72 | } 73 | } 74 | 75 | /** Same as [AlertDialog.show] but setting immersive mode in the dialog's window */ 76 | fun AlertDialog.showImmersive() { 77 | // Set the dialog to not focusable 78 | window.setFlags( 79 | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, 80 | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) 81 | 82 | // Make sure that the dialog's window is in full screen 83 | window.decorView.systemUiVisibility = FLAGS_FULLSCREEN 84 | 85 | // Show the dialog while still in immersive mode 86 | show() 87 | 88 | // Set the dialog to focusable again 89 | window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) 90 | } 91 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/color/selector_button_text.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/color/selector_ic.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/button_round_corners.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/ic_back.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 23 | 26 | 27 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/ic_delete.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 23 | 26 | 27 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 22 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 175 | 180 | 185 | 186 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/ic_outer_circle.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 23 | 26 | 27 | 28 | 29 | 30 | 33 | 36 | 37 | 38 | 39 | 40 | 43 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/ic_photo.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 23 | 26 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/ic_share.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 23 | 26 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/ic_shutter.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/ic_shutter_focused.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 22 | 25 | 28 | 29 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/ic_shutter_normal.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 22 | 25 | 28 | 29 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/ic_shutter_pressed.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 22 | 25 | 28 | 29 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/drawable/ic_switch.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 23 | 26 | 29 | 32 | 35 | 38 | 41 | 44 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/layout-land/camera_ui_container.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 23 | 24 | 25 | 38 | 39 | 50 | 51 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 23 | 24 | 31 | 32 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/layout/camera_ui_container.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 23 | 24 | 25 | 38 | 39 | 50 | 51 | 64 | 65 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/layout/fragment_camera.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 24 | 25 | 29 | 30 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/layout/fragment_gallery.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 22 | 23 | 27 | 28 | 32 | 33 | 45 | 46 | 59 | 60 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/navigation/nav_graph.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 22 | 23 | 27 | 30 | 31 | 32 | 36 | 39 | 43 | 44 | 45 | 49 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/values-v28/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | #3F51B5 19 | #303F9F 20 | #FF4081 21 | #FFFFFFFF 22 | #DDFFFFFF 23 | #AAFFFFFF 24 | 25 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 16dp 19 | 32dp 20 | 48dp 21 | 64dp 22 | 92dp 23 | 24 | 4dp 25 | 8dp 26 | 16dp 27 | 28 | 4dp 29 | 8dp 30 | 12dp 31 | 32 | 32dp 33 | 64dp 34 | 92dp 35 | 36 | 12dp 37 | 80dp 38 | 24dp 39 | 80dp 40 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/values/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FFFFFF 4 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | CameraX Basic 19 | Capture 20 | Switch camera 21 | Gallery 22 | Back 23 | Share 24 | Share using 25 | Camera 26 | HDR 27 | Night 28 | Delete 29 | Delete current photo? 30 | Confirm 31 | 32 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/main/res/xml/file_paths.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /CameraXBasic/app/src/test/java/com/android/example/cameraxbasic/MainInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.example.cameraxbasic 18 | 19 | import android.Manifest 20 | import android.content.Context 21 | import androidx.test.core.app.ApplicationProvider 22 | import androidx.test.ext.junit.runners.AndroidJUnit4 23 | import androidx.test.rule.ActivityTestRule 24 | import androidx.test.rule.GrantPermissionRule 25 | import org.junit.Assert.assertEquals 26 | import org.junit.Rule 27 | import org.junit.Test 28 | import org.junit.runner.RunWith 29 | 30 | @RunWith(AndroidJUnit4::class) 31 | class MainInstrumentedTest { 32 | 33 | @get:Rule 34 | val permissionRule = GrantPermissionRule.grant( 35 | Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO) 36 | 37 | @get:Rule 38 | val activityRule: ActivityTestRule = ActivityTestRule(MainActivity::class.java) 39 | 40 | @Test 41 | fun useAppContext() { 42 | // Context of the app under test 43 | val context = ApplicationProvider.getApplicationContext() as Context 44 | assertEquals("com.android.example.cameraxbasic", context.packageName) 45 | } 46 | } -------------------------------------------------------------------------------- /CameraXBasic/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 18 | 19 | buildscript { 20 | // Top-level variables used for versioning 21 | ext.kotlin_version = '+' 22 | ext.java_version = JavaVersion.VERSION_1_8 23 | 24 | repositories { 25 | google() 26 | jcenter() 27 | } 28 | dependencies { 29 | classpath 'com.android.tools.build:gradle:3.4.0' 30 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 31 | 32 | // NOTE: Do not place your application dependencies here; they belong 33 | // in the individual module build.gradle files 34 | } 35 | } 36 | 37 | allprojects { 38 | repositories { 39 | mavenLocal() 40 | google() 41 | jcenter() 42 | } 43 | } 44 | 45 | task clean(type: Delete) { 46 | delete rootProject.buildDir 47 | } 48 | -------------------------------------------------------------------------------- /CameraXBasic/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | android.enableJetifier=true 11 | android.useAndroidX=true 12 | android.enableUnitTestBinaryResources=true 13 | # When configured, Gradle will run in incubating parallel mode. 14 | # This option should only be used with decoupled projects. More details, visit 15 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 16 | # org.gradle.parallel=true 17 | -------------------------------------------------------------------------------- /CameraXBasic/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glumes/camera/e4754e23ed11e2b4505776b9107cdee13ea3cd5e/CameraXBasic/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /CameraXBasic/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Apr 26 17:04:07 AEST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip 7 | -------------------------------------------------------------------------------- /CameraXBasic/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /CameraXBasic/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /CameraXBasic/settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Google LLC 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | include ':app' 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Version 2.0, January 2004 2 | http://www.apache.org/licenses/ 3 | 4 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 5 | 6 | 1. Definitions. 7 | 8 | "License" shall mean the terms and conditions for use, reproduction, 9 | and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by 12 | the copyright owner that is granting the License. 13 | 14 | "Legal Entity" shall mean the union of the acting entity and all 15 | other entities that control, are controlled by, or are under common 16 | control with that entity. For the purposes of this definition, 17 | "control" means (i) the power, direct or indirect, to cause the 18 | direction or management of such entity, whether by contract or 19 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity 23 | exercising permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, 26 | including but not limited to software source code, documentation 27 | source, and configuration files. 28 | 29 | "Object" form shall mean any form resulting from mechanical 30 | transformation or translation of a Source form, including but 31 | not limited to compiled object code, generated documentation, 32 | and conversions to other media types. 33 | 34 | "Work" shall mean the work of authorship, whether in Source or 35 | Object form, made available under the License, as indicated by a 36 | copyright notice that is included in or attached to the work 37 | (an example is provided in the Appendix below). 38 | 39 | "Derivative Works" shall mean any work, whether in Source or Object 40 | form, that is based on (or derived from) the Work and for which the 41 | editorial revisions, annotations, elaborations, or other modifications 42 | represent, as a whole, an original work of authorship. For the purposes 43 | of this License, Derivative Works shall not include works that remain 44 | separable from, or merely link (or bind by name) to the interfaces of, 45 | the Work and Derivative Works thereof. 46 | 47 | "Contribution" shall mean any work of authorship, including 48 | the original version of the Work and any modifications or additions 49 | to that Work or Derivative Works thereof, that is intentionally 50 | submitted to Licensor for inclusion in the Work by the copyright owner 51 | or by an individual or Legal Entity authorized to submit on behalf of 52 | the copyright owner. For the purposes of this definition, "submitted" 53 | means any form of electronic, verbal, or written communication sent 54 | to the Licensor or its representatives, including but not limited to 55 | communication on electronic mailing lists, source code control systems, 56 | and issue tracking systems that are managed by, or on behalf of, the 57 | Licensor for the purpose of discussing and improving the Work, but 58 | excluding communication that is conspicuously marked or otherwise 59 | designated in writing by the copyright owner as "Not a Contribution." 60 | 61 | "Contributor" shall mean Licensor and any individual or Legal Entity 62 | on behalf of whom a Contribution has been received by Licensor and 63 | subsequently incorporated within the Work. 64 | 65 | 2. Grant of Copyright License. Subject to the terms and conditions of 66 | this License, each Contributor hereby grants to You a perpetual, 67 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 68 | copyright license to reproduce, prepare Derivative Works of, 69 | publicly display, publicly perform, sublicense, and distribute the 70 | Work and such Derivative Works in Source or Object form. 71 | 72 | 3. Grant of Patent License. Subject to the terms and conditions of 73 | this License, each Contributor hereby grants to You a perpetual, 74 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 75 | (except as stated in this section) patent license to make, have made, 76 | use, offer to sell, sell, import, and otherwise transfer the Work, 77 | where such license applies only to those patent claims licensable 78 | by such Contributor that are necessarily infringed by their 79 | Contribution(s) alone or by combination of their Contribution(s) 80 | with the Work to which such Contribution(s) was submitted. If You 81 | institute patent litigation against any entity (including a 82 | cross-claim or counterclaim in a lawsuit) alleging that the Work 83 | or a Contribution incorporated within the Work constitutes direct 84 | or contributory patent infringement, then any patent licenses 85 | granted to You under this License for that Work shall terminate 86 | as of the date such litigation is filed. 87 | 88 | 4. Redistribution. You may reproduce and distribute copies of the 89 | Work or Derivative Works thereof in any medium, with or without 90 | modifications, and in Source or Object form, provided that You 91 | meet the following conditions: 92 | 93 | (a) You must give any other recipients of the Work or 94 | Derivative Works a copy of this License; and 95 | 96 | (b) You must cause any modified files to carry prominent notices 97 | stating that You changed the files; and 98 | 99 | (c) You must retain, in the Source form of any Derivative Works 100 | that You distribute, all copyright, patent, trademark, and 101 | attribution notices from the Source form of the Work, 102 | excluding those notices that do not pertain to any part of 103 | the Derivative Works; and 104 | 105 | (d) If the Work includes a "NOTICE" text file as part of its 106 | distribution, then any Derivative Works that You distribute must 107 | include a readable copy of the attribution notices contained 108 | within such NOTICE file, excluding those notices that do not 109 | pertain to any part of the Derivative Works, in at least one 110 | of the following places: within a NOTICE text file distributed 111 | as part of the Derivative Works; within the Source form or 112 | documentation, if provided along with the Derivative Works; or, 113 | within a display generated by the Derivative Works, if and 114 | wherever such third-party notices normally appear. The contents 115 | of the NOTICE file are for informational purposes only and 116 | do not modify the License. You may add Your own attribution 117 | notices within Derivative Works that You distribute, alongside 118 | or as an addendum to the NOTICE text from the Work, provided 119 | that such additional attribution notices cannot be construed 120 | as modifying the License. 121 | 122 | You may add Your own copyright statement to Your modifications and 123 | may provide additional or different license terms and conditions 124 | for use, reproduction, or distribution of Your modifications, or 125 | for any such Derivative Works as a whole, provided Your use, 126 | reproduction, and distribution of the Work otherwise complies with 127 | the conditions stated in this License. 128 | 129 | 5. Submission of Contributions. Unless You explicitly state otherwise, 130 | any Contribution intentionally submitted for inclusion in the Work 131 | by You to the Licensor shall be under the terms and conditions of 132 | this License, without any additional terms or conditions. 133 | Notwithstanding the above, nothing herein shall supersede or modify 134 | the terms of any separate license agreement you may have executed 135 | with Licensor regarding such Contributions. 136 | 137 | 6. Trademarks. This License does not grant permission to use the trade 138 | names, trademarks, service marks, or product names of the Licensor, 139 | except as required for reasonable and customary use in describing the 140 | origin of the Work and reproducing the content of the NOTICE file. 141 | 142 | 7. Disclaimer of Warranty. Unless required by applicable law or 143 | agreed to in writing, Licensor provides the Work (and each 144 | Contributor provides its Contributions) on an "AS IS" BASIS, 145 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 146 | implied, including, without limitation, any warranties or conditions 147 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 148 | PARTICULAR PURPOSE. You are solely responsible for determining the 149 | appropriateness of using or redistributing the Work and assume any 150 | risks associated with Your exercise of permissions under this License. 151 | 152 | 8. Limitation of Liability. In no event and under no legal theory, 153 | whether in tort (including negligence), contract, or otherwise, 154 | unless required by applicable law (such as deliberate and grossly 155 | negligent acts) or agreed to in writing, shall any Contributor be 156 | liable to You for damages, including any direct, indirect, special, 157 | incidental, or consequential damages of any character arising as a 158 | result of this License or out of the use or inability to use the 159 | Work (including but not limited to damages for loss of goodwill, 160 | work stoppage, computer failure or malfunction, or any and all 161 | other commercial damages or losses), even if such Contributor 162 | has been advised of the possibility of such damages. 163 | 164 | 9. Accepting Warranty or Additional Liability. While redistributing 165 | the Work or Derivative Works thereof, You may choose to offer, 166 | and charge a fee for, acceptance of support, warranty, indemnity, 167 | or other liability obligations and/or rights consistent with this 168 | License. However, in accepting such obligations, You may act only 169 | on Your own behalf and on Your sole responsibility, not on behalf 170 | of any other Contributor, and only if You agree to indemnify, 171 | defend, and hold each Contributor harmless for any liability 172 | incurred by, or claims asserted against, such Contributor by reason 173 | of your accepting any such warranty or additional liability. 174 | 175 | END OF TERMS AND CONDITIONS 176 | 177 | Copyright 2019 Google LLC 178 | 179 | Licensed under the Apache License, Version 2.0 (the "License"); 180 | you may not use this file except in compliance with the License. 181 | You may obtain a copy of the License at 182 | 183 | http://www.apache.org/licenses/LICENSE-2.0 184 | 185 | Unless required by applicable law or agreed to in writing, software 186 | distributed under the License is distributed on an "AS IS" BASIS, 187 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 188 | See the License for the specific language governing permissions and 189 | limitations under the License. 190 | 191 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Camera Samples Repository 2 | ===================== 3 | 4 | This repository contains a set of individual Android Studio projects to help you get 5 | started with the Camera APIs in Android. 6 | 7 | License 8 | ------- 9 | 10 | Copyright 2019 Google, Inc. 11 | 12 | Licensed to the Apache Software Foundation (ASF) under one or more contributor 13 | license agreements. See the NOTICE file distributed with this work for 14 | additional information regarding copyright ownership. The ASF licenses this 15 | file to you under the Apache License, Version 2.0 (the "License"); you may not 16 | use this file except in compliance with the License. You may obtain a copy of 17 | the License at 18 | 19 | http://www.apache.org/licenses/LICENSE-2.0 20 | 21 | Unless required by applicable law or agreed to in writing, software 22 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 23 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 24 | License for the specific language governing permissions and limitations under 25 | the License. 26 | --------------------------------------------------------------------------------