Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.79 KB | None | 0 0
  1. package com.example.michail.photomanager;
  2.  
  3. import android.Manifest;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.pm.ActivityInfo;
  7. import android.content.pm.PackageManager;
  8. import android.graphics.Bitmap;
  9. import android.graphics.BitmapFactory;
  10. import android.graphics.Camera;
  11. import android.graphics.Canvas;
  12. import android.graphics.ImageFormat;
  13. import android.graphics.Rect;
  14. import android.graphics.SurfaceTexture;
  15. import android.graphics.YuvImage;
  16. import android.hardware.camera2.params.StreamConfigurationMap;
  17. import android.media.Image;
  18. import android.media.ImageReader;
  19. import android.media.MediaPlayer;
  20. import android.os.Build;
  21. import android.os.Environment;
  22. import android.os.Handler;
  23. import android.os.HandlerThread;
  24. import android.provider.MediaStore;
  25. import android.support.annotation.IntDef;
  26. import android.support.annotation.NonNull;
  27. import android.support.annotation.RequiresApi;
  28. //import android.support.annotation.Size;
  29. import android.support.v4.content.ContextCompat;
  30. import android.support.v7.app.AppCompatActivity;
  31. import android.os.Bundle;
  32.  
  33. import com.google.android.gms.vision.Frame;
  34. import com.google.android.gms.vision.barcode.Barcode;
  35. import com.google.android.gms.vision.barcode.BarcodeDetector;
  36.  
  37. import android.hardware.camera2.*;
  38. import android.text.style.TtsSpan;
  39. import android.util.Log;
  40. import android.util.Size;
  41. import android.util.SparseArray;
  42. import android.util.SparseIntArray;
  43. import android.view.Surface;
  44. import android.view.TextureView;
  45. import android.view.View;
  46. import android.widget.Button;
  47. import android.widget.ImageButton;
  48. import android.widget.Toast;
  49.  
  50. import java.io.ByteArrayInputStream;
  51. import java.io.ByteArrayOutputStream;
  52. import java.io.File;
  53. import java.io.FileNotFoundException;
  54. import java.io.FileOutputStream;
  55. import java.nio.ByteBuffer;
  56. import java.util.ArrayList;
  57. import java.util.Arrays;
  58. import java.util.Collection;
  59. import java.util.Collections;
  60. import java.util.Comparator;
  61. import java.util.List;
  62.  
  63.  
  64. public class MainActivity extends AppCompatActivity {
  65.  
  66. private static final int REQUEST_CAMERA_PERMISSION_RESULT = 0;
  67. public static String LOG_TAG = null;
  68. private TextureView mTextureView;
  69. private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {
  70. @Override
  71. public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
  72. //Toast.makeText(getApplicationContext(), "TextureView is available", Toast.LENGTH_SHORT).show();
  73. setupCamera(width, height);
  74. connectCamera();
  75.  
  76.  
  77. }
  78.  
  79. @Override
  80. public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {
  81.  
  82. }
  83.  
  84. @Override
  85. public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
  86. return false;
  87. }
  88.  
  89. @Override
  90. public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
  91.  
  92. }
  93. };
  94. CameraDevice mCameraDevice;
  95. private CameraDevice.StateCallback mCameraDeviceStateCallback = new CameraDevice.StateCallback() {
  96. @Override
  97. public void onOpened(@NonNull CameraDevice cameraDevice) {
  98. mCameraDevice = cameraDevice;
  99. startPreview();
  100.  
  101.  
  102. Toast.makeText(getApplicationContext(), "Camera connection made :)", Toast.LENGTH_SHORT).show();
  103.  
  104. }
  105.  
  106. @Override
  107. public void onDisconnected(@NonNull CameraDevice cameraDevice) {
  108. cameraDevice.close();
  109. mCameraDevice = null;
  110. }
  111.  
  112. @Override
  113. public void onError(@NonNull CameraDevice cameraDevice, int error) {
  114. cameraDevice.close();
  115. mCameraDevice = null;
  116. }
  117. };
  118.  
  119. private Surface mPreviewSurface;
  120. private HandlerThread mBackgroundHandlerThread;
  121. private Handler mBackgroundHandler;
  122. private String mCameraId;
  123. private Size mPreviewSize;
  124. private CaptureRequest.Builder mCaptureRequestBuilder;
  125. private ImageButton switch_On_or_Off;
  126. private boolean isFlashOn = false;
  127. private boolean hasFlash;
  128. private CameraCaptureSession mSession;
  129. private CameraCharacteristics mCameraCharacteristics;
  130. private ImageReader mImageReader;
  131. private Surface mImageReaderSurface;
  132.  
  133.  
  134. private static SparseIntArray ORIENTATIONS = new SparseIntArray();
  135.  
  136. static {
  137. ORIENTATIONS.append(Surface.ROTATION_0, 0);
  138. ORIENTATIONS.append(Surface.ROTATION_90, 90);
  139. ORIENTATIONS.append(Surface.ROTATION_180, 180);
  140. ORIENTATIONS.append(Surface.ROTATION_270, 0);
  141.  
  142.  
  143. }
  144.  
  145. private static class CompareSizeByArea implements Comparator<Size> {
  146.  
  147. @Override
  148. public int compare(Size lhs, Size rhs) {
  149. return Long.signum((long) lhs.getWidth() * lhs.getHeight() / (long) rhs.getWidth() * rhs.getHeight());
  150. }
  151.  
  152. }
  153.  
  154.  
  155. @Override
  156. protected void onCreate(Bundle savedInstanceState) {
  157. super.onCreate(savedInstanceState);
  158. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  159. setContentView(R.layout.activity_main);
  160. mTextureView = (TextureView) findViewById(R.id.textureView);
  161. switch_On_or_Off = (ImageButton) findViewById(R.id.imageButton);
  162. switch_On_or_Off.setOnClickListener(new View.OnClickListener() {
  163. @Override
  164. public void onClick(View view) {
  165. if (mCameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
  166. if (!isFlashOn) {
  167. turnOnFlash();
  168. isFlashOn = true;
  169. } else {
  170. turnOffFlash();
  171. isFlashOn = false;
  172. }
  173. } else {
  174. Toast.makeText(getApplicationContext(), "No flashlight on this device.", Toast.LENGTH_SHORT);
  175. }
  176. }
  177.  
  178.  
  179. });
  180.  
  181. }
  182.  
  183.  
  184. private void turnOnFlash() {
  185. mCaptureRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);
  186. try {
  187. mSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, null);
  188. } catch (CameraAccessException e) {
  189. e.printStackTrace();
  190. }
  191. }
  192.  
  193. private void turnOffFlash() {
  194. // TODO
  195. mCaptureRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF);
  196. try {
  197. mSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, null);
  198. } catch (CameraAccessException e) {
  199. e.printStackTrace();
  200. }
  201. }
  202.  
  203. @Override
  204. protected void onResume() {
  205. super.onResume();
  206. startBackgroundThread();
  207. if (mTextureView.isAvailable()) {
  208. setupCamera(mTextureView.getWidth(), mTextureView.getHeight());
  209. connectCamera();
  210.  
  211. } else {
  212. mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
  213. }
  214. }
  215.  
  216.  
  217. @Override
  218. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  219. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  220. if (requestCode == REQUEST_CAMERA_PERMISSION_RESULT) {
  221. if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
  222. Toast.makeText(getApplicationContext(), "Application will not run without camera services", Toast.LENGTH_SHORT).show();
  223.  
  224. }
  225. }
  226. }
  227.  
  228. @Override
  229. protected void onPause() {
  230. closeCamera();
  231. stopBackgroundThread();
  232. super.onPause();
  233.  
  234. }
  235.  
  236. @Override
  237. public void onWindowFocusChanged(boolean hasFocus) {
  238. super.onWindowFocusChanged(hasFocus);
  239. View decorView = getWindow().getDecorView();
  240. if (hasFocus) {
  241. decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
  242. | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
  243. | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
  244. | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
  245. | View.SYSTEM_UI_FLAG_FULLSCREEN
  246. | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
  247.  
  248. }
  249. }
  250.  
  251. private void setupCamera(int width, int height) {
  252. CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
  253. try {
  254. for (String cameraId : cameraManager.getCameraIdList()) {
  255. mCameraCharacteristics = (CameraCharacteristics) cameraManager.getCameraCharacteristics(cameraId);
  256. if (mCameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) {
  257. continue;
  258. }
  259. StreamConfigurationMap map = mCameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
  260. int deviceOrientation = getWindowManager().getDefaultDisplay().getRotation();
  261. int totalRotation = sensorToDeviceRotation(mCameraCharacteristics, deviceOrientation);
  262. boolean swapRotation = totalRotation == 90 || totalRotation == 270;
  263. int rotatedWidth = width;
  264. int rotatedHeight = height;
  265. if (swapRotation) {
  266. rotatedWidth = height;
  267. rotatedHeight = width;
  268. }
  269. mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedWidth, rotatedHeight);
  270. mImageReader = ImageReader.newInstance(mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.YUV_420_888, 5000);
  271. //mImageReader = ImageReader.newInstance(320, 240, ImageFormat.JPEG, 1);
  272. mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
  273. mImageReaderSurface = mImageReader.getSurface();
  274. mCameraId = cameraId;
  275. return;
  276. }
  277.  
  278. } catch (CameraAccessException e) {
  279. e.printStackTrace();
  280. }
  281. }
  282.  
  283. private void connectCamera() {
  284. CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
  285.  
  286. try {
  287. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  288. if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
  289. cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
  290. } else {
  291. if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
  292. Toast.makeText(this, "Video app required access to camera", Toast.LENGTH_SHORT).show();
  293. }
  294. requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION_RESULT);
  295. }
  296.  
  297. } else {
  298. cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
  299. }
  300.  
  301.  
  302. } catch (CameraAccessException e) {
  303. e.printStackTrace();
  304. }
  305. }
  306.  
  307. private ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {
  308.  
  309. @Override
  310. public void onImageAvailable(ImageReader imageReader) {
  311. Image image = mImageReader.acquireLatestImage();
  312. Log.i("sdfsdf", "hey ");
  313. //processImage(image);
  314. image.close();
  315. }
  316. };
  317.  
  318. public void processImage(Image image) {
  319. Toast.makeText(getApplicationContext(), "ooh", Toast.LENGTH_SHORT).show();
  320. ByteBuffer buffer = image.getPlanes()[0].getBuffer();
  321. byte[] bytes = new byte[buffer.remaining()];
  322. buffer.get(bytes, 0, bytes.length);
  323. /*YuvImage yuvimage = new YuvImage(bytes, ImageFormat.NV21, mPreviewSize.getWidth(), mPreviewSize.getHeight(), null);
  324. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  325. yuvimage.compressToJpeg(new Rect(0, 0, 10 , 10 ), 100, baos); // Where 100 is the quality of the generated jpeg
  326. byte[] jpegArray = baos.toByteArray();*/
  327. Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  328.  
  329. //byte[] bytes = new byte[buffer.remaining()];
  330. //buffer.get(bytes, 0 , bytes.length );
  331. //Bitmap mBitmapForBarcodeEncode = Bitmap.createBitmap(mPreviewSize.getWidth() , mPreviewSize.getHeight() , Bitmap.Config.ARGB_8888);
  332. // mBitmapForBarcodeEncode.copyPixelsFromBuffer(buffer);
  333. //this.decodeMyBarcode(bitmap);
  334. }
  335.  
  336. private void startPreview() {
  337. SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
  338. surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
  339.  
  340. final Surface previewSurface = new Surface(surfaceTexture);
  341. try {
  342. mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
  343. mCaptureRequestBuilder.addTarget(previewSurface);
  344. mCaptureRequestBuilder.addTarget(mImageReaderSurface);
  345.  
  346. mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, mImageReaderSurface), new CameraCaptureSession.StateCallback() {
  347. @RequiresApi(api = Build.VERSION_CODES.M)
  348. @Override
  349. public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
  350. try {
  351. mPreviewSurface = previewSurface;
  352. //mPreviewSurface.lockHardwareCanvas();
  353. //mPreviewSurface.lockCanvas(new Rect());
  354. //Log.i("surf" , );
  355. //mPreviewSurface.unlockCanvasAndPost(new Canvas());
  356. mSession = cameraCaptureSession;
  357. mSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, null);
  358. } catch (CameraAccessException e) {
  359. e.printStackTrace();
  360. }
  361. }
  362.  
  363. @Override
  364. public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
  365. Toast.makeText(getApplicationContext(), "Unable to setup camera preview", Toast.LENGTH_SHORT).show();
  366.  
  367. }
  368. }, null);
  369.  
  370. } catch (CameraAccessException e) {
  371. e.printStackTrace();
  372. }
  373.  
  374. }
  375.  
  376. private void closeCamera() {
  377. if (mCameraDevice != null) {
  378. mCameraDevice.close();
  379. mCameraDevice = null;
  380. }
  381. }
  382.  
  383. private void startBackgroundThread() {
  384. mBackgroundHandlerThread = new HandlerThread("Camera2");
  385. mBackgroundHandlerThread.start();
  386. mBackgroundHandler = new Handler(mBackgroundHandlerThread.getLooper());
  387. }
  388.  
  389. private void stopBackgroundThread() {
  390. mBackgroundHandlerThread.quitSafely();
  391. try {
  392. mBackgroundHandlerThread.join();
  393. mBackgroundHandlerThread = null;
  394. mBackgroundHandler = null;
  395. } catch (InterruptedException e) {
  396. e.printStackTrace();
  397. }
  398.  
  399. }
  400.  
  401. private static int sensorToDeviceRotation(CameraCharacteristics cameraCharacteristics, int deviceOrientation) {
  402. int sensorOrientation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
  403. deviceOrientation = ORIENTATIONS.get(deviceOrientation);
  404. return (sensorOrientation + deviceOrientation + 360) % 360;
  405. }
  406.  
  407. private static Size chooseOptimalSize(Size[] choices, int width, int height) {
  408. List<Size> bigEnough = new ArrayList<Size>();
  409. for (Size option : choices) {
  410. if (option.getHeight() == option.getWidth() * height / width && option.getWidth() >= width && option.getHeight() >= height) {
  411. bigEnough.add(option);
  412. }
  413. }
  414. if (bigEnough.size() > 0) {
  415. return Collections.min(bigEnough, new CompareSizeByArea());
  416. } else {
  417. return choices[0];
  418. }
  419. }
  420.  
  421. private void decodeMyBarcode(Bitmap bitmap) {
  422. BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(getApplicationContext())
  423. .setBarcodeFormats(Barcode.ALL_FORMATS).build();
  424. if (!barcodeDetector.isOperational()) {
  425. Toast.makeText(getApplicationContext(), "Could not set up the detector!", Toast.LENGTH_SHORT).show();
  426. }
  427. Frame frame = new Frame.Builder().setBitmap(bitmap).build();
  428. SparseArray<Barcode> barcodes = barcodeDetector.detect(frame);
  429. if (barcodes.size() != 0) {
  430. Barcode thisCode = barcodes.valueAt(0);
  431. Log.i("detect", thisCode.rawValue);
  432. }
  433. }
  434.  
  435.  
  436. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement