Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.michail.photomanager;
- import android.Manifest;
- import android.content.Context;
- import android.content.Intent;
- import android.content.pm.ActivityInfo;
- import android.content.pm.PackageManager;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Camera;
- import android.graphics.Canvas;
- import android.graphics.ImageFormat;
- import android.graphics.Rect;
- import android.graphics.SurfaceTexture;
- import android.graphics.YuvImage;
- import android.hardware.camera2.params.StreamConfigurationMap;
- import android.media.Image;
- import android.media.ImageReader;
- import android.media.MediaPlayer;
- import android.os.Build;
- import android.os.Environment;
- import android.os.Handler;
- import android.os.HandlerThread;
- import android.provider.MediaStore;
- import android.support.annotation.IntDef;
- import android.support.annotation.NonNull;
- import android.support.annotation.RequiresApi;
- //import android.support.annotation.Size;
- import android.support.v4.content.ContextCompat;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import com.google.android.gms.vision.Frame;
- import com.google.android.gms.vision.barcode.Barcode;
- import com.google.android.gms.vision.barcode.BarcodeDetector;
- import android.hardware.camera2.*;
- import android.text.style.TtsSpan;
- import android.util.Log;
- import android.util.Size;
- import android.util.SparseArray;
- import android.util.SparseIntArray;
- import android.view.Surface;
- import android.view.TextureView;
- import android.view.View;
- import android.widget.Button;
- import android.widget.ImageButton;
- import android.widget.Toast;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.nio.ByteBuffer;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Collection;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- public class MainActivity extends AppCompatActivity {
- private static final int REQUEST_CAMERA_PERMISSION_RESULT = 0;
- public static String LOG_TAG = null;
- private TextureView mTextureView;
- private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {
- @Override
- public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
- //Toast.makeText(getApplicationContext(), "TextureView is available", Toast.LENGTH_SHORT).show();
- setupCamera(width, height);
- connectCamera();
- }
- @Override
- public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {
- }
- @Override
- public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
- return false;
- }
- @Override
- public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
- }
- };
- CameraDevice mCameraDevice;
- private CameraDevice.StateCallback mCameraDeviceStateCallback = new CameraDevice.StateCallback() {
- @Override
- public void onOpened(@NonNull CameraDevice cameraDevice) {
- mCameraDevice = cameraDevice;
- startPreview();
- Toast.makeText(getApplicationContext(), "Camera connection made :)", Toast.LENGTH_SHORT).show();
- }
- @Override
- public void onDisconnected(@NonNull CameraDevice cameraDevice) {
- cameraDevice.close();
- mCameraDevice = null;
- }
- @Override
- public void onError(@NonNull CameraDevice cameraDevice, int error) {
- cameraDevice.close();
- mCameraDevice = null;
- }
- };
- private Surface mPreviewSurface;
- private HandlerThread mBackgroundHandlerThread;
- private Handler mBackgroundHandler;
- private String mCameraId;
- private Size mPreviewSize;
- private CaptureRequest.Builder mCaptureRequestBuilder;
- private ImageButton switch_On_or_Off;
- private boolean isFlashOn = false;
- private boolean hasFlash;
- private CameraCaptureSession mSession;
- private CameraCharacteristics mCameraCharacteristics;
- private ImageReader mImageReader;
- private Surface mImageReaderSurface;
- private static SparseIntArray ORIENTATIONS = new SparseIntArray();
- static {
- ORIENTATIONS.append(Surface.ROTATION_0, 0);
- ORIENTATIONS.append(Surface.ROTATION_90, 90);
- ORIENTATIONS.append(Surface.ROTATION_180, 180);
- ORIENTATIONS.append(Surface.ROTATION_270, 0);
- }
- private static class CompareSizeByArea implements Comparator<Size> {
- @Override
- public int compare(Size lhs, Size rhs) {
- return Long.signum((long) lhs.getWidth() * lhs.getHeight() / (long) rhs.getWidth() * rhs.getHeight());
- }
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- setContentView(R.layout.activity_main);
- mTextureView = (TextureView) findViewById(R.id.textureView);
- switch_On_or_Off = (ImageButton) findViewById(R.id.imageButton);
- switch_On_or_Off.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if (mCameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
- if (!isFlashOn) {
- turnOnFlash();
- isFlashOn = true;
- } else {
- turnOffFlash();
- isFlashOn = false;
- }
- } else {
- Toast.makeText(getApplicationContext(), "No flashlight on this device.", Toast.LENGTH_SHORT);
- }
- }
- });
- }
- private void turnOnFlash() {
- mCaptureRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);
- try {
- mSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, null);
- } catch (CameraAccessException e) {
- e.printStackTrace();
- }
- }
- private void turnOffFlash() {
- // TODO
- mCaptureRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF);
- try {
- mSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, null);
- } catch (CameraAccessException e) {
- e.printStackTrace();
- }
- }
- @Override
- protected void onResume() {
- super.onResume();
- startBackgroundThread();
- if (mTextureView.isAvailable()) {
- setupCamera(mTextureView.getWidth(), mTextureView.getHeight());
- connectCamera();
- } else {
- mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
- }
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults);
- if (requestCode == REQUEST_CAMERA_PERMISSION_RESULT) {
- if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
- Toast.makeText(getApplicationContext(), "Application will not run without camera services", Toast.LENGTH_SHORT).show();
- }
- }
- }
- @Override
- protected void onPause() {
- closeCamera();
- stopBackgroundThread();
- super.onPause();
- }
- @Override
- public void onWindowFocusChanged(boolean hasFocus) {
- super.onWindowFocusChanged(hasFocus);
- View decorView = getWindow().getDecorView();
- if (hasFocus) {
- decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
- | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
- | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
- | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
- | View.SYSTEM_UI_FLAG_FULLSCREEN
- | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
- }
- }
- private void setupCamera(int width, int height) {
- CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
- try {
- for (String cameraId : cameraManager.getCameraIdList()) {
- mCameraCharacteristics = (CameraCharacteristics) cameraManager.getCameraCharacteristics(cameraId);
- if (mCameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) {
- continue;
- }
- StreamConfigurationMap map = mCameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
- int deviceOrientation = getWindowManager().getDefaultDisplay().getRotation();
- int totalRotation = sensorToDeviceRotation(mCameraCharacteristics, deviceOrientation);
- boolean swapRotation = totalRotation == 90 || totalRotation == 270;
- int rotatedWidth = width;
- int rotatedHeight = height;
- if (swapRotation) {
- rotatedWidth = height;
- rotatedHeight = width;
- }
- mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedWidth, rotatedHeight);
- mImageReader = ImageReader.newInstance(mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.YUV_420_888, 5000);
- //mImageReader = ImageReader.newInstance(320, 240, ImageFormat.JPEG, 1);
- mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
- mImageReaderSurface = mImageReader.getSurface();
- mCameraId = cameraId;
- return;
- }
- } catch (CameraAccessException e) {
- e.printStackTrace();
- }
- }
- private void connectCamera() {
- CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
- try {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
- cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
- } else {
- if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
- Toast.makeText(this, "Video app required access to camera", Toast.LENGTH_SHORT).show();
- }
- requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION_RESULT);
- }
- } else {
- cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
- }
- } catch (CameraAccessException e) {
- e.printStackTrace();
- }
- }
- private ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {
- @Override
- public void onImageAvailable(ImageReader imageReader) {
- Image image = mImageReader.acquireLatestImage();
- Log.i("sdfsdf", "hey ");
- //processImage(image);
- image.close();
- }
- };
- public void processImage(Image image) {
- Toast.makeText(getApplicationContext(), "ooh", Toast.LENGTH_SHORT).show();
- ByteBuffer buffer = image.getPlanes()[0].getBuffer();
- byte[] bytes = new byte[buffer.remaining()];
- buffer.get(bytes, 0, bytes.length);
- /*YuvImage yuvimage = new YuvImage(bytes, ImageFormat.NV21, mPreviewSize.getWidth(), mPreviewSize.getHeight(), null);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- yuvimage.compressToJpeg(new Rect(0, 0, 10 , 10 ), 100, baos); // Where 100 is the quality of the generated jpeg
- byte[] jpegArray = baos.toByteArray();*/
- Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
- //byte[] bytes = new byte[buffer.remaining()];
- //buffer.get(bytes, 0 , bytes.length );
- //Bitmap mBitmapForBarcodeEncode = Bitmap.createBitmap(mPreviewSize.getWidth() , mPreviewSize.getHeight() , Bitmap.Config.ARGB_8888);
- // mBitmapForBarcodeEncode.copyPixelsFromBuffer(buffer);
- //this.decodeMyBarcode(bitmap);
- }
- private void startPreview() {
- SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
- surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
- final Surface previewSurface = new Surface(surfaceTexture);
- try {
- mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
- mCaptureRequestBuilder.addTarget(previewSurface);
- mCaptureRequestBuilder.addTarget(mImageReaderSurface);
- mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, mImageReaderSurface), new CameraCaptureSession.StateCallback() {
- @RequiresApi(api = Build.VERSION_CODES.M)
- @Override
- public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
- try {
- mPreviewSurface = previewSurface;
- //mPreviewSurface.lockHardwareCanvas();
- //mPreviewSurface.lockCanvas(new Rect());
- //Log.i("surf" , );
- //mPreviewSurface.unlockCanvasAndPost(new Canvas());
- mSession = cameraCaptureSession;
- mSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, null);
- } catch (CameraAccessException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
- Toast.makeText(getApplicationContext(), "Unable to setup camera preview", Toast.LENGTH_SHORT).show();
- }
- }, null);
- } catch (CameraAccessException e) {
- e.printStackTrace();
- }
- }
- private void closeCamera() {
- if (mCameraDevice != null) {
- mCameraDevice.close();
- mCameraDevice = null;
- }
- }
- private void startBackgroundThread() {
- mBackgroundHandlerThread = new HandlerThread("Camera2");
- mBackgroundHandlerThread.start();
- mBackgroundHandler = new Handler(mBackgroundHandlerThread.getLooper());
- }
- private void stopBackgroundThread() {
- mBackgroundHandlerThread.quitSafely();
- try {
- mBackgroundHandlerThread.join();
- mBackgroundHandlerThread = null;
- mBackgroundHandler = null;
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- private static int sensorToDeviceRotation(CameraCharacteristics cameraCharacteristics, int deviceOrientation) {
- int sensorOrientation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
- deviceOrientation = ORIENTATIONS.get(deviceOrientation);
- return (sensorOrientation + deviceOrientation + 360) % 360;
- }
- private static Size chooseOptimalSize(Size[] choices, int width, int height) {
- List<Size> bigEnough = new ArrayList<Size>();
- for (Size option : choices) {
- if (option.getHeight() == option.getWidth() * height / width && option.getWidth() >= width && option.getHeight() >= height) {
- bigEnough.add(option);
- }
- }
- if (bigEnough.size() > 0) {
- return Collections.min(bigEnough, new CompareSizeByArea());
- } else {
- return choices[0];
- }
- }
- private void decodeMyBarcode(Bitmap bitmap) {
- BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(getApplicationContext())
- .setBarcodeFormats(Barcode.ALL_FORMATS).build();
- if (!barcodeDetector.isOperational()) {
- Toast.makeText(getApplicationContext(), "Could not set up the detector!", Toast.LENGTH_SHORT).show();
- }
- Frame frame = new Frame.Builder().setBitmap(bitmap).build();
- SparseArray<Barcode> barcodes = barcodeDetector.detect(frame);
- if (barcodes.size() != 0) {
- Barcode thisCode = barcodes.valueAt(0);
- Log.i("detect", thisCode.rawValue);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement