Advertisement
Combreal

customCamera01.java

Aug 6th, 2022
898
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.90 KB | None
  1. -----------------------------activity_main.xml
  2.  
  3.  
  4.  
  5. <?xml version="1.0" encoding="utf-8"?>
  6. <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  7.     xmlns:app="http://schemas.android.com/apk/res-auto"
  8.     xmlns:tools="http://schemas.android.com/tools"
  9.     android:layout_width="match_parent"
  10.     android:layout_height="match_parent"
  11.     tools:context=".MainActivity">
  12.  
  13.     <LinearLayout
  14.         android:layout_width="match_parent"
  15.         android:layout_height="0dp"
  16.         android:orientation="vertical"
  17.         android:weightSum="100"
  18.         app:layout_constraintBottom_toBottomOf="parent"
  19.         app:layout_constraintEnd_toEndOf="parent"
  20.         app:layout_constraintStart_toStartOf="parent"
  21.         app:layout_constraintTop_toTopOf="parent">
  22.  
  23.         <androidx.camera.view.PreviewView
  24.             android:id="@+id/previewView"
  25.             android:layout_width="match_parent"
  26.             android:layout_height="0dp"
  27.             android:layout_weight="90" />
  28.  
  29.         <RelativeLayout
  30.             android:layout_width="match_parent"
  31.             android:layout_height="0dp"
  32.             android:orientation="horizontal"
  33.             android:layout_weight="10"
  34.             app:layout_constraintBottom_toBottomOf="parent"
  35.             app:layout_constraintEnd_toEndOf="parent"
  36.             app:layout_constraintStart_toStartOf="parent"
  37.             app:layout_constraintTop_toTopOf="parent">
  38.  
  39.             <Button
  40.                 android:id="@+id/bCapture"
  41.                 android:layout_width="match_parent"
  42.                 android:layout_height="match_parent"
  43.                 android:text="take picture" />
  44.  
  45.         </RelativeLayout>
  46.     </LinearLayout>
  47.  
  48. </androidx.constraintlayout.widget.ConstraintLayout>
  49.  
  50.  
  51.  
  52. -----------------------------AndroidManifest.xml
  53.  
  54.  
  55.  
  56. <?xml version="1.0" encoding="utf-8"?>
  57. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  58.     xmlns:tools="http://schemas.android.com/tools"
  59.     package="com.example.camera_devandroid_01">
  60.  
  61.     <uses-permission android:name="android.permission.CAMERA"/>
  62.     <uses-permission android:name="android.permission.RECORD_AUDIO"/>
  63.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!-- android:maxSdkVersion="28" -->
  64.     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  65.     <uses-feature android:name="android.hardware.camera" />
  66.  
  67.     <application
  68.         android:allowBackup="true"
  69.         android:dataExtractionRules="@xml/data_extraction_rules"
  70.         android:fullBackupContent="@xml/backup_rules"
  71.         android:icon="@mipmap/ic_launcher"
  72.         android:label="@string/app_name"
  73.         android:roundIcon="@mipmap/ic_launcher_round"
  74.         android:supportsRtl="true"
  75.         android:theme="@style/Theme.Cameradevandroid01"
  76.         tools:targetApi="31">
  77.         <activity
  78.             android:name=".MainActivity"
  79.             android:exported="true">
  80.             <intent-filter>
  81.                 <action android:name="android.intent.action.MAIN" />
  82.  
  83.                 <category android:name="android.intent.category.LAUNCHER" />
  84.             </intent-filter>
  85.         </activity>
  86.     </application>
  87.  
  88. </manifest>
  89.  
  90.  
  91.  
  92. -----------------------------build.gradle
  93.  
  94.  
  95.  
  96. plugins {
  97.     id 'com.android.application'
  98. }
  99.  
  100. android {
  101.     compileSdk 32
  102.  
  103.     defaultConfig {
  104.         applicationId "com.example.camera_devandroid_01"
  105.         minSdk 23
  106.         targetSdk 32
  107.         versionCode 1
  108.         versionName "1.0"
  109.  
  110.         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
  111.     }
  112.  
  113.     buildTypes {
  114.         release {
  115.             minifyEnabled false
  116.             proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  117.         }
  118.     }
  119.     compileOptions {
  120.         sourceCompatibility JavaVersion.VERSION_1_8
  121.         targetCompatibility JavaVersion.VERSION_1_8
  122.     }
  123. }
  124.  
  125. dependencies {
  126.  
  127.     implementation 'androidx.appcompat:appcompat:1.4.2'
  128.     implementation 'com.google.android.material:material:1.6.1'
  129.     implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
  130.     def cameraxVersion = "1.1.0-alpha05"
  131.     implementation "androidx.camera:camera-core:${cameraxVersion}"
  132.     implementation "androidx.camera:camera-camera2:${cameraxVersion}"
  133.     implementation "androidx.camera:camera-lifecycle:${cameraxVersion}"
  134.  
  135.     implementation 'androidx.camera:camera-view:1.0.0-alpha25'
  136.  
  137.     testImplementation 'junit:junit:4.13.2'
  138.     androidTestImplementation 'androidx.test.ext:junit:1.1.3'
  139.     androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
  140. }
  141.  
  142.  
  143.  
  144. -----------------------------MainActivity.java
  145.  
  146.  
  147.  
  148. package com.example.camera_devandroid_01;
  149.  
  150. import androidx.annotation.NonNull;
  151. import androidx.appcompat.app.AppCompatActivity;
  152. import androidx.camera.core.CameraSelector;
  153. import androidx.camera.core.ImageAnalysis;
  154. import androidx.camera.core.ImageCapture;
  155. import androidx.camera.core.ImageCaptureException;
  156. import androidx.camera.core.ImageProxy;
  157. import androidx.camera.core.Preview;
  158. import androidx.camera.core.VideoCapture;
  159. import androidx.camera.lifecycle.ProcessCameraProvider;
  160. import androidx.camera.view.PreviewView;
  161. import androidx.core.content.ContextCompat;
  162. import androidx.lifecycle.LifecycleOwner;
  163.  
  164. import android.Manifest;
  165. import android.annotation.SuppressLint;
  166. import android.app.Activity;
  167. import android.content.ContentValues;
  168. import android.content.Context;
  169. import android.content.pm.PackageManager;
  170. import android.hardware.Camera;
  171. import android.os.Bundle;
  172. import android.provider.MediaStore;
  173. import android.util.Log;
  174. import android.view.View;
  175. import android.widget.Button;
  176. import android.widget.Toast;
  177.  
  178. import com.google.common.util.concurrent.ListenableFuture;
  179.  
  180. import java.util.concurrent.ExecutionException;
  181.  
  182. public class MainActivity extends AppCompatActivity {
  183.  
  184.     private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
  185.     PreviewView previewView;
  186.     private ImageCapture imageCapture;
  187.     private Button bCapture;
  188.  
  189.     @Override
  190.     protected void onCreate(Bundle savedInstanceState) {
  191.         super.onCreate(savedInstanceState);
  192.         setContentView(R.layout.activity_main);
  193.  
  194.         previewView = findViewById(R.id.previewView);
  195.         bCapture = findViewById(R.id.bCapture);
  196.  
  197.         if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_DENIED ||
  198.                 checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_DENIED ||
  199.                 checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED ||
  200.                 checkSelfPermission(Manifest.permission.INTERNET) == PackageManager.PERMISSION_DENIED ||
  201.                 checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED ||
  202.                 checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
  203.             String[] permission = {Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.INTERNET, Manifest.permission.WRITE_EXTERNAL_STORAGE};
  204.             requestPermissions(permission, 1000);
  205.         }
  206.  
  207.         cameraProviderFuture = ProcessCameraProvider.getInstance(this);
  208.         cameraProviderFuture.addListener(() -> {
  209.             try {
  210.                 ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
  211.                 startCameraX(cameraProvider);
  212.             } catch (ExecutionException | InterruptedException e) {
  213.                 e.printStackTrace();
  214.             }
  215.         }, ContextCompat.getMainExecutor(this));
  216.  
  217.         bCapture.setOnClickListener(new View.OnClickListener() {
  218.             @Override
  219.             public void onClick(View v) {
  220.                 //Toast.makeText(MainActivity.this, "Clicked Capture!", Toast.LENGTH_SHORT).show();
  221.                 capturePhoto();
  222.             }
  223.         });
  224.     }
  225.  
  226.     @SuppressLint("RestrictedApi")
  227.     private void startCameraX(@NonNull ProcessCameraProvider cameraProvider) {
  228.         cameraProvider.unbindAll();
  229.         CameraSelector cameraSelector = new CameraSelector.Builder()
  230.                 .requireLensFacing(CameraSelector.LENS_FACING_BACK)
  231.                 .build();
  232.         Preview preview = new Preview.Builder()
  233.                 .build();
  234.         preview.setSurfaceProvider(previewView.getSurfaceProvider());
  235.  
  236.         // Image capture use case
  237.         imageCapture = new ImageCapture.Builder()
  238.                 .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
  239.                 .build();
  240.  
  241.         // Image analysis use case
  242.         ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
  243.                 .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
  244.                 .build();
  245.  
  246.         //imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this),this);         //got to fix 'this' 2nd param
  247.         imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this), new ImageAnalysis.Analyzer() {
  248.             @Override
  249.             public void analyze(@NonNull ImageProxy imageProxy) {
  250.                 int rotationDegrees = imageProxy.getImageInfo().getRotationDegrees();
  251.                 imageProxy.close();
  252.             }
  253.         });
  254.  
  255.         //bind to lifecycle:
  256.         try {
  257.             cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview, imageCapture);
  258.         } catch (Exception e) {
  259.             Log.e("========>ERROR<=========", e.getMessage(), e);
  260.         }
  261.     }
  262.  
  263.     private void capturePhoto() {
  264.         long timestamp = System.currentTimeMillis();
  265.  
  266.         ContentValues contentValues = new ContentValues();
  267.         contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, timestamp);
  268.         contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
  269.  
  270.         imageCapture.takePicture(
  271.                 new ImageCapture.OutputFileOptions.Builder(
  272.                         getContentResolver(),
  273.                         MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
  274.                         contentValues
  275.                 ).build(),
  276.                 ContextCompat.getMainExecutor(this),
  277.                 new ImageCapture.OnImageSavedCallback() {
  278.                     @Override
  279.                     public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
  280.                         Toast.makeText(MainActivity.this, "Photo has been saved successfully.", Toast.LENGTH_SHORT).show();
  281.                     }
  282.  
  283.                     @Override
  284.                     public void onError(@NonNull ImageCaptureException exception) {
  285.                         Toast.makeText(MainActivity.this, "Error saving photo: " + exception.getMessage(), Toast.LENGTH_SHORT).show();
  286.                     }
  287.                 }
  288.         );
  289.     }
  290. }
  291.  
Advertisement
RAW Paste Data Copied
Advertisement