CameraUtil.java revision 8ee16b8a323ffa20e6fb1270d498ec445f64defc
1/* 2 * Copyright (C) 2009 The Android Open Source Project 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 * http://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 17package com.android.camera.util; 18 19import android.app.Activity; 20import android.app.AlertDialog; 21import android.app.admin.DevicePolicyManager; 22import android.content.ActivityNotFoundException; 23import android.content.ComponentName; 24import android.content.ContentResolver; 25import android.content.Context; 26import android.content.DialogInterface; 27import android.content.Intent; 28import android.content.res.TypedArray; 29import android.graphics.Bitmap; 30import android.graphics.BitmapFactory; 31import android.graphics.Matrix; 32import android.graphics.Point; 33import android.graphics.PointF; 34import android.graphics.Rect; 35import android.graphics.RectF; 36import android.hardware.camera2.CameraCharacteristics; 37import android.hardware.camera2.CameraMetadata; 38import android.location.Location; 39import android.net.Uri; 40import android.os.ParcelFileDescriptor; 41import android.telephony.TelephonyManager; 42import android.util.DisplayMetrics; 43import android.util.TypedValue; 44import android.view.OrientationEventListener; 45import android.view.Surface; 46import android.view.View; 47import android.view.WindowManager; 48import android.view.animation.AlphaAnimation; 49import android.view.animation.Animation; 50import android.widget.Toast; 51 52import com.android.camera.CameraActivity; 53import com.android.camera.CameraDisabledException; 54import com.android.camera.data.FilmstripItem; 55import com.android.camera.debug.Log; 56import com.android.camera2.R; 57import com.android.ex.camera2.portability.CameraCapabilities; 58import com.android.ex.camera2.portability.CameraSettings; 59 60import java.io.Closeable; 61import java.io.IOException; 62import java.lang.reflect.Method; 63import java.text.SimpleDateFormat; 64import java.util.Date; 65import java.util.List; 66import java.util.Locale; 67 68/** 69 * Collection of utility functions used in this package. 70 */ 71public class CameraUtil { 72 private static final Log.Tag TAG = new Log.Tag("Util"); 73 74 // For calculate the best fps range for still image capture. 75 private final static int MAX_PREVIEW_FPS_TIMES_1000 = 400000; 76 private final static int PREFERRED_PREVIEW_FPS_TIMES_1000 = 30000; 77 78 // For creating crop intents. 79 public static final String KEY_RETURN_DATA = "return-data"; 80 public static final String KEY_SHOW_WHEN_LOCKED = "showWhenLocked"; 81 82 /** Orientation hysteresis amount used in rounding, in degrees. */ 83 public static final int ORIENTATION_HYSTERESIS = 5; 84 85 public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW"; 86 /** See android.hardware.Camera.ACTION_NEW_PICTURE. */ 87 public static final String ACTION_NEW_PICTURE = "android.hardware.action.NEW_PICTURE"; 88 /** See android.hardware.Camera.ACTION_NEW_VIDEO. */ 89 public static final String ACTION_NEW_VIDEO = "android.hardware.action.NEW_VIDEO"; 90 91 /** 92 * Broadcast Action: The camera application has become active in 93 * picture-taking mode. 94 */ 95 public static final String ACTION_CAMERA_STARTED = "com.android.camera.action.CAMERA_STARTED"; 96 /** 97 * Broadcast Action: The camera application is no longer in active 98 * picture-taking mode. 99 */ 100 public static final String ACTION_CAMERA_STOPPED = "com.android.camera.action.CAMERA_STOPPED"; 101 /** 102 * When the camera application is active in picture-taking mode, it listens 103 * for this intent, which upon receipt will trigger the shutter to capture a 104 * new picture, as if the user had pressed the shutter button. 105 */ 106 public static final String ACTION_CAMERA_SHUTTER_CLICK = 107 "com.android.camera.action.SHUTTER_CLICK"; 108 109 // Fields for the show-on-maps-functionality 110 private static final String MAPS_PACKAGE_NAME = "com.google.android.apps.maps"; 111 private static final String MAPS_CLASS_NAME = "com.google.android.maps.MapsActivity"; 112 113 /** Has to be in sync with the receiving MovieActivity. */ 114 public static final String KEY_TREAT_UP_AS_BACK = "treat-up-as-back"; 115 116 /** Private intent extras. Test only. */ 117 private static final String EXTRAS_CAMERA_FACING = 118 "android.intent.extras.CAMERA_FACING"; 119 120 private static float sPixelDensity = 1; 121 private static ImageFileNamer sImageFileNamer; 122 123 private CameraUtil() { 124 } 125 126 public static void initialize(Context context) { 127 DisplayMetrics metrics = new DisplayMetrics(); 128 WindowManager wm = (WindowManager) 129 context.getSystemService(Context.WINDOW_SERVICE); 130 wm.getDefaultDisplay().getMetrics(metrics); 131 sPixelDensity = metrics.density; 132 sImageFileNamer = new ImageFileNamer( 133 context.getString(R.string.image_file_name_format)); 134 } 135 136 public static int dpToPixel(int dp) { 137 return Math.round(sPixelDensity * dp); 138 } 139 140 /** 141 * Rotates the bitmap by the specified degree. If a new bitmap is created, 142 * the original bitmap is recycled. 143 */ 144 public static Bitmap rotate(Bitmap b, int degrees) { 145 return rotateAndMirror(b, degrees, false); 146 } 147 148 /** 149 * Rotates and/or mirrors the bitmap. If a new bitmap is created, the 150 * original bitmap is recycled. 151 */ 152 public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) { 153 if ((degrees != 0 || mirror) && b != null) { 154 Matrix m = new Matrix(); 155 // Mirror first. 156 // horizontal flip + rotation = -rotation + horizontal flip 157 if (mirror) { 158 m.postScale(-1, 1); 159 degrees = (degrees + 360) % 360; 160 if (degrees == 0 || degrees == 180) { 161 m.postTranslate(b.getWidth(), 0); 162 } else if (degrees == 90 || degrees == 270) { 163 m.postTranslate(b.getHeight(), 0); 164 } else { 165 throw new IllegalArgumentException("Invalid degrees=" + degrees); 166 } 167 } 168 if (degrees != 0) { 169 // clockwise 170 m.postRotate(degrees, 171 (float) b.getWidth() / 2, (float) b.getHeight() / 2); 172 } 173 174 try { 175 Bitmap b2 = Bitmap.createBitmap( 176 b, 0, 0, b.getWidth(), b.getHeight(), m, true); 177 if (b != b2) { 178 b.recycle(); 179 b = b2; 180 } 181 } catch (OutOfMemoryError ex) { 182 // We have no memory to rotate. Return the original bitmap. 183 } 184 } 185 return b; 186 } 187 188 /** 189 * Compute the sample size as a function of minSideLength and 190 * maxNumOfPixels. minSideLength is used to specify that minimal width or 191 * height of a bitmap. maxNumOfPixels is used to specify the maximal size in 192 * pixels that is tolerable in terms of memory usage. The function returns a 193 * sample size based on the constraints. 194 * <p> 195 * Both size and minSideLength can be passed in as -1 which indicates no 196 * care of the corresponding constraint. The functions prefers returning a 197 * sample size that generates a smaller bitmap, unless minSideLength = -1. 198 * <p> 199 * Also, the function rounds up the sample size to a power of 2 or multiple 200 * of 8 because BitmapFactory only honors sample size this way. For example, 201 * BitmapFactory downsamples an image by 2 even though the request is 3. So 202 * we round up the sample size to avoid OOM. 203 */ 204 public static int computeSampleSize(BitmapFactory.Options options, 205 int minSideLength, int maxNumOfPixels) { 206 int initialSize = computeInitialSampleSize(options, minSideLength, 207 maxNumOfPixels); 208 209 int roundedSize; 210 if (initialSize <= 8) { 211 roundedSize = 1; 212 while (roundedSize < initialSize) { 213 roundedSize <<= 1; 214 } 215 } else { 216 roundedSize = (initialSize + 7) / 8 * 8; 217 } 218 219 return roundedSize; 220 } 221 222 private static int computeInitialSampleSize(BitmapFactory.Options options, 223 int minSideLength, int maxNumOfPixels) { 224 double w = options.outWidth; 225 double h = options.outHeight; 226 227 int lowerBound = (maxNumOfPixels < 0) ? 1 : 228 (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); 229 int upperBound = (minSideLength < 0) ? 128 : 230 (int) Math.min(Math.floor(w / minSideLength), 231 Math.floor(h / minSideLength)); 232 233 if (upperBound < lowerBound) { 234 // return the larger one when there is no overlapping zone. 235 return lowerBound; 236 } 237 238 if (maxNumOfPixels < 0 && minSideLength < 0) { 239 return 1; 240 } else if (minSideLength < 0) { 241 return lowerBound; 242 } else { 243 return upperBound; 244 } 245 } 246 247 public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) { 248 try { 249 BitmapFactory.Options options = new BitmapFactory.Options(); 250 options.inJustDecodeBounds = true; 251 BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 252 options); 253 if (options.mCancel || options.outWidth == -1 254 || options.outHeight == -1) { 255 return null; 256 } 257 options.inSampleSize = computeSampleSize( 258 options, -1, maxNumOfPixels); 259 options.inJustDecodeBounds = false; 260 261 options.inDither = false; 262 options.inPreferredConfig = Bitmap.Config.ARGB_8888; 263 return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 264 options); 265 } catch (OutOfMemoryError ex) { 266 Log.e(TAG, "Got oom exception ", ex); 267 return null; 268 } 269 } 270 271 public static void closeSilently(Closeable c) { 272 if (c == null) { 273 return; 274 } 275 try { 276 c.close(); 277 } catch (Throwable t) { 278 // do nothing 279 } 280 } 281 282 public static void Assert(boolean cond) { 283 if (!cond) { 284 throw new AssertionError(); 285 } 286 } 287 288 public static void showErrorAndFinish(final Activity activity, int msgId) { 289 DialogInterface.OnClickListener buttonListener = 290 new DialogInterface.OnClickListener() { 291 @Override 292 public void onClick(DialogInterface dialog, int which) { 293 activity.finish(); 294 } 295 }; 296 TypedValue out = new TypedValue(); 297 activity.getTheme().resolveAttribute(android.R.attr.alertDialogIcon, out, true); 298 // Some crash reports indicate users leave app prior to this dialog 299 // appearing, so check to ensure that the activity is not shutting down 300 // before attempting to attach a dialog to the window manager. 301 if (!activity.isFinishing()) { 302 Log.e(TAG, "Show fatal error dialog"); 303 new AlertDialog.Builder(activity) 304 .setCancelable(false) 305 .setTitle(R.string.camera_error_title) 306 .setMessage(msgId) 307 .setNeutralButton(R.string.dialog_ok, buttonListener) 308 .setIcon(out.resourceId) 309 .show(); 310 } 311 } 312 313 public static <T> T checkNotNull(T object) { 314 if (object == null) { 315 throw new NullPointerException(); 316 } 317 return object; 318 } 319 320 public static boolean equals(Object a, Object b) { 321 return (a == b) || (a == null ? false : a.equals(b)); 322 } 323 324 public static int nextPowerOf2(int n) { 325 // TODO: what happens if n is negative or already a power of 2? 326 n -= 1; 327 n |= n >>> 16; 328 n |= n >>> 8; 329 n |= n >>> 4; 330 n |= n >>> 2; 331 n |= n >>> 1; 332 return n + 1; 333 } 334 335 public static float distance(float x, float y, float sx, float sy) { 336 float dx = x - sx; 337 float dy = y - sy; 338 return (float) Math.sqrt(dx * dx + dy * dy); 339 } 340 341 /** 342 * Clamps x to between min and max (inclusive on both ends, x = min --> min, 343 * x = max --> max). 344 */ 345 public static int clamp(int x, int min, int max) { 346 if (x > max) { 347 return max; 348 } 349 if (x < min) { 350 return min; 351 } 352 return x; 353 } 354 355 /** 356 * Clamps x to between min and max (inclusive on both ends, x = min --> min, 357 * x = max --> max). 358 */ 359 public static float clamp(float x, float min, float max) { 360 if (x > max) { 361 return max; 362 } 363 if (x < min) { 364 return min; 365 } 366 return x; 367 } 368 369 /** 370 * Linear interpolation between a and b by the fraction t. t = 0 --> a, t = 371 * 1 --> b. 372 */ 373 public static float lerp(float a, float b, float t) { 374 return a + t * (b - a); 375 } 376 377 /** 378 * Given (nx, ny) \in [0, 1]^2, in the display's portrait coordinate system, 379 * returns normalized sensor coordinates \in [0, 1]^2 depending on how the 380 * sensor's orientation \in {0, 90, 180, 270}. 381 * <p> 382 * Returns null if sensorOrientation is not one of the above. 383 * </p> 384 */ 385 public static PointF normalizedSensorCoordsForNormalizedDisplayCoords( 386 float nx, float ny, int sensorOrientation) { 387 switch (sensorOrientation) { 388 case 0: 389 return new PointF(nx, ny); 390 case 90: 391 return new PointF(ny, 1.0f - nx); 392 case 180: 393 return new PointF(1.0f - nx, 1.0f - ny); 394 case 270: 395 return new PointF(1.0f - ny, nx); 396 default: 397 return null; 398 } 399 } 400 401 /** 402 * Given a size, return the largest size with the given aspectRatio that 403 * maximally fits into the bounding rectangle of the original Size. 404 * 405 * @param size the original Size to crop 406 * @param aspectRatio the target aspect ratio 407 * @return the largest Size with the given aspect ratio that is smaller than 408 * or equal to the original Size. 409 */ 410 public static Size constrainToAspectRatio(Size size, float aspectRatio) { 411 float width = size.getWidth(); 412 float height = size.getHeight(); 413 414 float currentAspectRatio = width * 1.0f / height; 415 416 if (currentAspectRatio > aspectRatio) { 417 // chop longer side 418 if (width > height) { 419 width = height * aspectRatio; 420 } else { 421 height = width / aspectRatio; 422 } 423 } else if (currentAspectRatio < aspectRatio) { 424 // chop shorter side 425 if (width < height) { 426 width = height * aspectRatio; 427 } else { 428 height = width / aspectRatio; 429 } 430 } 431 432 return new Size((int) width, (int) height); 433 } 434 435 public static int getDisplayRotation(Context context) { 436 WindowManager windowManager = (WindowManager) context 437 .getSystemService(Context.WINDOW_SERVICE); 438 int rotation = windowManager.getDefaultDisplay() 439 .getRotation(); 440 switch (rotation) { 441 case Surface.ROTATION_0: 442 return 0; 443 case Surface.ROTATION_90: 444 return 90; 445 case Surface.ROTATION_180: 446 return 180; 447 case Surface.ROTATION_270: 448 return 270; 449 } 450 return 0; 451 } 452 453 private static Size getDefaultDisplaySize(Context context) { 454 WindowManager windowManager = (WindowManager) context 455 .getSystemService(Context.WINDOW_SERVICE); 456 Point res = new Point(); 457 windowManager.getDefaultDisplay().getSize(res); 458 return new Size(res); 459 } 460 461 public static Size getOptimalPreviewSize( 462 Context context, List<Size> sizes, double targetRatio) { 463 int optimalPickIndex = getOptimalPreviewSizeIndex(context, sizes, targetRatio); 464 if (optimalPickIndex == -1) { 465 return null; 466 } else { 467 return sizes.get(optimalPickIndex); 468 } 469 } 470 471 /** 472 * Returns the index into 'sizes' that is most optimal given the current 473 * screen and target aspect ratio.. 474 * <p> 475 * This is using a default aspect ratio tolerance. If the tolerance is to be 476 * given you should call 477 * {@link #getOptimalPreviewSizeIndex(Context, List, double, Double)} 478 * 479 * @param context used to get the screen dimensions. TODO: Refactor to take 480 * in screen dimensions directly 481 * @param previewSizes the available preview sizes 482 * @param targetRatio the target aspect ratio, typically the aspect ratio of 483 * the picture size 484 * @return The index into 'previewSizes' for the optimal size, or -1, if no 485 * matching size was found. 486 */ 487 public static int getOptimalPreviewSizeIndex(Context context, 488 List<Size> sizes, double targetRatio) { 489 // Use a very small tolerance because we want an exact match. HTC 4:3 490 // ratios is over .01 from true 4:3, so this value must be above .01, 491 // see b/18241645. 492 final double aspectRatioTolerance = 0.02; 493 494 return getOptimalPreviewSizeIndex(context, sizes, targetRatio, aspectRatioTolerance); 495 } 496 497 /** 498 * Returns the index into 'sizes' that is most optimal given the current 499 * screen, target aspect ratio and tolerance. 500 * 501 * @param context used to get the screen dimensions. TODO: Refactor to take 502 * in screen dimensions directly 503 * @param previewSizes the available preview sizes 504 * @param targetRatio the target aspect ratio, typically the aspect ratio of 505 * the picture size 506 * @param aspectRatioTolerance the tolerance we allow between the selected 507 * preview size's aspect ratio and the target ratio. If this is 508 * set to 'null', the default value is used. 509 * @return The index into 'previewSizes' for the optimal size, or -1, if no 510 * matching size was found. 511 */ 512 public static int getOptimalPreviewSizeIndex(Context context, 513 List<Size> previewSizes, double targetRatio, Double aspectRatioTolerance) { 514 if (previewSizes == null) { 515 return -1; 516 } 517 518 // If no particular aspect ratio tolerance is set, use the default 519 // value. 520 if (aspectRatioTolerance == null) { 521 return getOptimalPreviewSizeIndex(context, previewSizes, targetRatio); 522 } 523 524 int optimalSizeIndex = -1; 525 double minDiff = Double.MAX_VALUE; 526 527 // Because of bugs of overlay and layout, we sometimes will try to 528 // layout the viewfinder in the portrait orientation and thus get the 529 // wrong size of preview surface. When we change the preview size, the 530 // new overlay will be created before the old one closed, which causes 531 // an exception. For now, just get the screen size. 532 Size defaultDisplaySize = getDefaultDisplaySize(context); 533 int targetHeight = Math.min(defaultDisplaySize.getWidth(), defaultDisplaySize.getHeight()); 534 // Try to find an size match aspect ratio and size 535 for (int i = 0; i < previewSizes.size(); i++) { 536 Size size = previewSizes.get(i); 537 double ratio = (double) size.getWidth() / size.getHeight(); 538 if (Math.abs(ratio - targetRatio) > aspectRatioTolerance) { 539 continue; 540 } 541 542 double heightDiff = Math.abs(size.getHeight() - targetHeight); 543 if (heightDiff < minDiff) { 544 optimalSizeIndex = i; 545 minDiff = heightDiff; 546 } else if (heightDiff == minDiff) { 547 // Prefer resolutions smaller-than-display when an equally close 548 // larger-than-display resolution is available 549 if (size.getHeight() < targetHeight) { 550 optimalSizeIndex = i; 551 minDiff = heightDiff; 552 } 553 } 554 } 555 // Cannot find the one match the aspect ratio. This should not happen. 556 // Ignore the requirement. 557 if (optimalSizeIndex == -1) { 558 Log.w(TAG, "No preview size match the aspect ratio. available sizes: " + previewSizes); 559 minDiff = Double.MAX_VALUE; 560 for (int i = 0; i < previewSizes.size(); i++) { 561 Size size = previewSizes.get(i); 562 if (Math.abs(size.getHeight() - targetHeight) < minDiff) { 563 optimalSizeIndex = i; 564 minDiff = Math.abs(size.getHeight() - targetHeight); 565 } 566 } 567 } 568 569 return optimalSizeIndex; 570 } 571 572 /** 573 * Returns the largest picture size which matches the given aspect ratio, 574 * except for the special WYSIWYG case where the picture size exactly 575 * matches the target size. 576 * 577 * @param sizes a list of candidate sizes, available for use 578 * @param targetWidth the ideal width of the video snapshot 579 * @param targetHeight the ideal height of the video snapshot 580 * @return the Optimal Video Snapshot Picture Size 581 */ 582 public static Size getOptimalVideoSnapshotPictureSize( 583 List<Size> sizes, int targetWidth, 584 int targetHeight) { 585 586 // Use a very small tolerance because we want an exact match. 587 final double ASPECT_TOLERANCE = 0.001; 588 if (sizes == null) { 589 return null; 590 } 591 592 Size optimalSize = null; 593 594 // WYSIWYG Override 595 // We assume that physical display constraints have already been 596 // imposed on the variables sizes 597 for (Size size : sizes) { 598 if (size.height() == targetHeight && size.width() == targetWidth) { 599 return size; 600 } 601 } 602 603 // Try to find a size matches aspect ratio and has the largest width 604 final double targetRatio = (double) targetWidth / targetHeight; 605 for (Size size : sizes) { 606 double ratio = (double) size.width() / size.height(); 607 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) { 608 continue; 609 } 610 if (optimalSize == null || size.width() > optimalSize.width()) { 611 optimalSize = size; 612 } 613 } 614 615 // Cannot find one that matches the aspect ratio. This should not 616 // happen. Ignore the requirement. 617 if (optimalSize == null) { 618 Log.w(TAG, "No picture size match the aspect ratio"); 619 for (Size size : sizes) { 620 if (optimalSize == null || size.width() > optimalSize.width()) { 621 optimalSize = size; 622 } 623 } 624 } 625 return optimalSize; 626 } 627 628 /** 629 * Returns whether the device is voice-capable (meaning, it can do MMS). 630 */ 631 public static boolean isMmsCapable(Context context) { 632 TelephonyManager telephonyManager = (TelephonyManager) 633 context.getSystemService(Context.TELEPHONY_SERVICE); 634 if (telephonyManager == null) { 635 return false; 636 } 637 638 try { 639 Class<?> partypes[] = new Class[0]; 640 Method sIsVoiceCapable = TelephonyManager.class.getMethod( 641 "isVoiceCapable", partypes); 642 643 Object arglist[] = new Object[0]; 644 Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist); 645 return (Boolean) retobj; 646 } catch (java.lang.reflect.InvocationTargetException ite) { 647 // Failure, must be another device. 648 // Assume that it is voice capable. 649 } catch (IllegalAccessException iae) { 650 // Failure, must be an other device. 651 // Assume that it is voice capable. 652 } catch (NoSuchMethodException nsme) { 653 } 654 return true; 655 } 656 657 // This is for test only. Allow the camera to launch the specific camera. 658 public static int getCameraFacingIntentExtras(Activity currentActivity) { 659 int cameraId = -1; 660 661 int intentCameraId = 662 currentActivity.getIntent().getIntExtra(CameraUtil.EXTRAS_CAMERA_FACING, -1); 663 664 if (isFrontCameraIntent(intentCameraId)) { 665 // Check if the front camera exist 666 int frontCameraId = ((CameraActivity) currentActivity).getCameraProvider() 667 .getFirstFrontCameraId(); 668 if (frontCameraId != -1) { 669 cameraId = frontCameraId; 670 } 671 } else if (isBackCameraIntent(intentCameraId)) { 672 // Check if the back camera exist 673 int backCameraId = ((CameraActivity) currentActivity).getCameraProvider() 674 .getFirstBackCameraId(); 675 if (backCameraId != -1) { 676 cameraId = backCameraId; 677 } 678 } 679 return cameraId; 680 } 681 682 private static boolean isFrontCameraIntent(int intentCameraId) { 683 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT); 684 } 685 686 private static boolean isBackCameraIntent(int intentCameraId) { 687 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK); 688 } 689 690 private static int sLocation[] = new int[2]; 691 692 // This method is not thread-safe. 693 public static boolean pointInView(float x, float y, View v) { 694 v.getLocationInWindow(sLocation); 695 return x >= sLocation[0] && x < (sLocation[0] + v.getWidth()) 696 && y >= sLocation[1] && y < (sLocation[1] + v.getHeight()); 697 } 698 699 public static int[] getRelativeLocation(View reference, View view) { 700 reference.getLocationInWindow(sLocation); 701 int referenceX = sLocation[0]; 702 int referenceY = sLocation[1]; 703 view.getLocationInWindow(sLocation); 704 sLocation[0] -= referenceX; 705 sLocation[1] -= referenceY; 706 return sLocation; 707 } 708 709 public static boolean isUriValid(Uri uri, ContentResolver resolver) { 710 if (uri == null) { 711 return false; 712 } 713 714 try { 715 ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r"); 716 if (pfd == null) { 717 Log.e(TAG, "Fail to open URI. URI=" + uri); 718 return false; 719 } 720 pfd.close(); 721 } catch (IOException ex) { 722 return false; 723 } 724 return true; 725 } 726 727 public static void dumpRect(RectF rect, String msg) { 728 Log.v(TAG, msg + "=(" + rect.left + "," + rect.top 729 + "," + rect.right + "," + rect.bottom + ")"); 730 } 731 732 public static void inlineRectToRectF(RectF rectF, Rect rect) { 733 rect.left = Math.round(rectF.left); 734 rect.top = Math.round(rectF.top); 735 rect.right = Math.round(rectF.right); 736 rect.bottom = Math.round(rectF.bottom); 737 } 738 739 public static Rect rectFToRect(RectF rectF) { 740 Rect rect = new Rect(); 741 inlineRectToRectF(rectF, rect); 742 return rect; 743 } 744 745 public static RectF rectToRectF(Rect r) { 746 return new RectF(r.left, r.top, r.right, r.bottom); 747 } 748 749 public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation, 750 int viewWidth, int viewHeight) { 751 // Need mirror for front camera. 752 matrix.setScale(mirror ? -1 : 1, 1); 753 // This is the value for android.hardware.Camera.setDisplayOrientation. 754 matrix.postRotate(displayOrientation); 755 // Camera driver coordinates range from (-1000, -1000) to (1000, 1000). 756 // UI coordinates range from (0, 0) to (width, height). 757 matrix.postScale(viewWidth / 2000f, viewHeight / 2000f); 758 matrix.postTranslate(viewWidth / 2f, viewHeight / 2f); 759 } 760 761 public static String createJpegName(long dateTaken) { 762 synchronized (sImageFileNamer) { 763 return sImageFileNamer.generateName(dateTaken); 764 } 765 } 766 767 public static void broadcastNewPicture(Context context, Uri uri) { 768 context.sendBroadcast(new Intent(ACTION_NEW_PICTURE, uri)); 769 // Keep compatibility 770 context.sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri)); 771 } 772 773 public static void fadeIn(View view, float startAlpha, float endAlpha, long duration) { 774 if (view.getVisibility() == View.VISIBLE) { 775 return; 776 } 777 778 view.setVisibility(View.VISIBLE); 779 Animation animation = new AlphaAnimation(startAlpha, endAlpha); 780 animation.setDuration(duration); 781 view.startAnimation(animation); 782 } 783 784 /** 785 * Down-samples a jpeg byte array. 786 * 787 * @param data a byte array of jpeg data 788 * @param downSampleFactor down-sample factor 789 * @return decoded and down-sampled bitmap 790 */ 791 public static Bitmap downSample(final byte[] data, int downSampleFactor) { 792 final BitmapFactory.Options opts = new BitmapFactory.Options(); 793 // Downsample the image 794 opts.inSampleSize = downSampleFactor; 795 return BitmapFactory.decodeByteArray(data, 0, data.length, opts); 796 } 797 798 public static void setGpsParameters(CameraSettings settings, Location loc) { 799 // Clear previous GPS location from the parameters. 800 settings.clearGpsData(); 801 802 boolean hasLatLon = false; 803 double lat; 804 double lon; 805 // Set GPS location. 806 if (loc != null) { 807 lat = loc.getLatitude(); 808 lon = loc.getLongitude(); 809 hasLatLon = (lat != 0.0d) || (lon != 0.0d); 810 } 811 812 if (!hasLatLon) { 813 // We always encode GpsTimeStamp even if the GPS location is not 814 // available. 815 settings.setGpsData( 816 new CameraSettings.GpsData(0f, 0f, 0f, System.currentTimeMillis() / 1000, null) 817 ); 818 } else { 819 Log.d(TAG, "Set gps location"); 820 // for NETWORK_PROVIDER location provider, we may have 821 // no altitude information, but the driver needs it, so 822 // we fake one. 823 // Location.getTime() is UTC in milliseconds. 824 // gps-timestamp is UTC in seconds. 825 long utcTimeSeconds = loc.getTime() / 1000; 826 settings.setGpsData(new CameraSettings.GpsData(loc.getLatitude(), loc.getLongitude(), 827 (loc.hasAltitude() ? loc.getAltitude() : 0), 828 (utcTimeSeconds != 0 ? utcTimeSeconds : System.currentTimeMillis()), 829 loc.getProvider().toUpperCase())); 830 } 831 } 832 833 /** 834 * For still image capture, we need to get the right fps range such that the 835 * camera can slow down the framerate to allow for less-noisy/dark 836 * viewfinder output in dark conditions. 837 * 838 * @param capabilities Camera's capabilities. 839 * @return null if no appropiate fps range can't be found. Otherwise, return 840 * the right range. 841 */ 842 public static int[] getPhotoPreviewFpsRange(CameraCapabilities capabilities) { 843 return getPhotoPreviewFpsRange(capabilities.getSupportedPreviewFpsRange()); 844 } 845 846 public static int[] getPhotoPreviewFpsRange(List<int[]> frameRates) { 847 if (frameRates.size() == 0) { 848 Log.e(TAG, "No suppoted frame rates returned!"); 849 return null; 850 } 851 852 // Find the lowest min rate in supported ranges who can cover 30fps. 853 int lowestMinRate = MAX_PREVIEW_FPS_TIMES_1000; 854 for (int[] rate : frameRates) { 855 int minFps = rate[0]; 856 int maxFps = rate[1]; 857 if (maxFps >= PREFERRED_PREVIEW_FPS_TIMES_1000 && 858 minFps <= PREFERRED_PREVIEW_FPS_TIMES_1000 && 859 minFps < lowestMinRate) { 860 lowestMinRate = minFps; 861 } 862 } 863 864 // Find all the modes with the lowest min rate found above, the pick the 865 // one with highest max rate. 866 int resultIndex = -1; 867 int highestMaxRate = 0; 868 for (int i = 0; i < frameRates.size(); i++) { 869 int[] rate = frameRates.get(i); 870 int minFps = rate[0]; 871 int maxFps = rate[1]; 872 if (minFps == lowestMinRate && highestMaxRate < maxFps) { 873 highestMaxRate = maxFps; 874 resultIndex = i; 875 } 876 } 877 878 if (resultIndex >= 0) { 879 return frameRates.get(resultIndex); 880 } 881 Log.e(TAG, "Can't find an appropiate frame rate range!"); 882 return null; 883 } 884 885 public static int[] getMaxPreviewFpsRange(List<int[]> frameRates) { 886 if (frameRates != null && frameRates.size() > 0) { 887 // The list is sorted. Return the last element. 888 return frameRates.get(frameRates.size() - 1); 889 } 890 return new int[0]; 891 } 892 893 public static void throwIfCameraDisabled(Context context) throws CameraDisabledException { 894 // Check if device policy has disabled the camera. 895 DevicePolicyManager dpm = 896 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); 897 if (dpm.getCameraDisabled(null)) { 898 throw new CameraDisabledException(); 899 } 900 } 901 902 /** 903 * Generates a 1d Gaussian mask of the input array size, and store the mask 904 * in the input array. 905 * 906 * @param mask empty array of size n, where n will be used as the size of 907 * the Gaussian mask, and the array will be populated with the 908 * values of the mask. 909 */ 910 private static void getGaussianMask(float[] mask) { 911 int len = mask.length; 912 int mid = len / 2; 913 float sigma = len; 914 float sum = 0; 915 for (int i = 0; i <= mid; i++) { 916 float ex = (float) Math.exp(-(i - mid) * (i - mid) / (mid * mid)) 917 / (2 * sigma * sigma); 918 int symmetricIndex = len - 1 - i; 919 mask[i] = ex; 920 mask[symmetricIndex] = ex; 921 sum += mask[i]; 922 if (i != symmetricIndex) { 923 sum += mask[symmetricIndex]; 924 } 925 } 926 927 for (int i = 0; i < mask.length; i++) { 928 mask[i] /= sum; 929 } 930 931 } 932 933 /** 934 * Add two pixels together where the second pixel will be applied with a 935 * weight. 936 * 937 * @param pixel pixel color value of weight 1 938 * @param newPixel second pixel color value where the weight will be applied 939 * @param weight a float weight that will be applied to the second pixel 940 * color 941 * @return the weighted addition of the two pixels 942 */ 943 public static int addPixel(int pixel, int newPixel, float weight) { 944 // TODO: scale weight to [0, 1024] to avoid casting to float and back to 945 // int. 946 int r = ((pixel & 0x00ff0000) + (int) ((newPixel & 0x00ff0000) * weight)) & 0x00ff0000; 947 int g = ((pixel & 0x0000ff00) + (int) ((newPixel & 0x0000ff00) * weight)) & 0x0000ff00; 948 int b = ((pixel & 0x000000ff) + (int) ((newPixel & 0x000000ff) * weight)) & 0x000000ff; 949 return 0xff000000 | r | g | b; 950 } 951 952 /** 953 * Apply blur to the input image represented in an array of colors and put 954 * the output image, in the form of an array of colors, into the output 955 * array. 956 * 957 * @param src source array of colors 958 * @param out output array of colors after the blur 959 * @param w width of the image 960 * @param h height of the image 961 * @param size size of the Gaussian blur mask 962 */ 963 public static void blur(int[] src, int[] out, int w, int h, int size) { 964 float[] k = new float[size]; 965 int off = size / 2; 966 967 getGaussianMask(k); 968 969 int[] tmp = new int[src.length]; 970 971 // Apply the 1d Gaussian mask horizontally to the image and put the 972 // intermediat results in a temporary array. 973 int rowPointer = 0; 974 for (int y = 0; y < h; y++) { 975 for (int x = 0; x < w; x++) { 976 int sum = 0; 977 for (int i = 0; i < k.length; i++) { 978 int dx = x + i - off; 979 dx = clamp(dx, 0, w - 1); 980 sum = addPixel(sum, src[rowPointer + dx], k[i]); 981 } 982 tmp[x + rowPointer] = sum; 983 } 984 rowPointer += w; 985 } 986 987 // Apply the 1d Gaussian mask vertically to the intermediate array, and 988 // the final results will be stored in the output array. 989 for (int x = 0; x < w; x++) { 990 rowPointer = 0; 991 for (int y = 0; y < h; y++) { 992 int sum = 0; 993 for (int i = 0; i < k.length; i++) { 994 int dy = y + i - off; 995 dy = clamp(dy, 0, h - 1); 996 sum = addPixel(sum, tmp[dy * w + x], k[i]); 997 } 998 out[x + rowPointer] = sum; 999 rowPointer += w; 1000 } 1001 } 1002 } 1003 1004 /** 1005 * Calculates a new dimension to fill the bound with the original aspect 1006 * ratio preserved. 1007 * 1008 * @param imageWidth The original width. 1009 * @param imageHeight The original height. 1010 * @param imageRotation The clockwise rotation in degrees of the image which 1011 * the original dimension comes from. 1012 * @param boundWidth The width of the bound. 1013 * @param boundHeight The height of the bound. 1014 * @returns The final width/height stored in Point.x/Point.y to fill the 1015 * bounds and preserve image aspect ratio. 1016 */ 1017 public static Point resizeToFill(int imageWidth, int imageHeight, int imageRotation, 1018 int boundWidth, int boundHeight) { 1019 if (imageRotation % 180 != 0) { 1020 // Swap width and height. 1021 int savedWidth = imageWidth; 1022 imageWidth = imageHeight; 1023 imageHeight = savedWidth; 1024 } 1025 1026 Point p = new Point(); 1027 p.x = boundWidth; 1028 p.y = boundHeight; 1029 1030 if (imageWidth * boundHeight > boundWidth * imageHeight) { 1031 p.y = imageHeight * p.x / imageWidth; 1032 } else { 1033 p.x = imageWidth * p.y / imageHeight; 1034 } 1035 1036 return p; 1037 } 1038 1039 private static class ImageFileNamer { 1040 private final SimpleDateFormat mFormat; 1041 1042 // The date (in milliseconds) used to generate the last name. 1043 private long mLastDate; 1044 1045 // Number of names generated for the same second. 1046 private int mSameSecondCount; 1047 1048 public ImageFileNamer(String format) { 1049 mFormat = new SimpleDateFormat(format); 1050 } 1051 1052 public String generateName(long dateTaken) { 1053 Date date = new Date(dateTaken); 1054 String result = mFormat.format(date); 1055 1056 // If the last name was generated for the same second, 1057 // we append _1, _2, etc to the name. 1058 if (dateTaken / 1000 == mLastDate / 1000) { 1059 mSameSecondCount++; 1060 result += "_" + mSameSecondCount; 1061 } else { 1062 mLastDate = dateTaken; 1063 mSameSecondCount = 0; 1064 } 1065 1066 return result; 1067 } 1068 } 1069 1070 public static void playVideo(CameraActivity activity, Uri uri, String title) { 1071 try { 1072 boolean isSecureCamera = activity.isSecureCamera(); 1073 if (!isSecureCamera) { 1074 Intent intent = IntentHelper.getVideoPlayerIntent(uri) 1075 .putExtra(Intent.EXTRA_TITLE, title) 1076 .putExtra(KEY_TREAT_UP_AS_BACK, true); 1077 activity.launchActivityByIntent(intent); 1078 } else { 1079 // In order not to send out any intent to be intercepted and 1080 // show the lock screen immediately, we just let the secure 1081 // camera activity finish. 1082 activity.finish(); 1083 } 1084 } catch (ActivityNotFoundException e) { 1085 Toast.makeText(activity, activity.getString(R.string.video_err), 1086 Toast.LENGTH_SHORT).show(); 1087 } 1088 } 1089 1090 /** 1091 * Starts GMM with the given location shown. If this fails, and GMM could 1092 * not be found, we use a geo intent as a fallback. 1093 * 1094 * @param activity the activity to use for launching the Maps intent. 1095 * @param latLong a 2-element array containing {latitude/longitude}. 1096 */ 1097 public static void showOnMap(Activity activity, double[] latLong) { 1098 try { 1099 // We don't use "geo:latitude,longitude" because it only centers 1100 // the MapView to the specified location, but we need a marker 1101 // for further operations (routing to/from). 1102 // The q=(lat, lng) syntax is suggested by geo-team. 1103 String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?f=q&q=(%f,%f)", 1104 latLong[0], latLong[1]); 1105 ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME, 1106 MAPS_CLASS_NAME); 1107 Intent mapsIntent = new Intent(Intent.ACTION_VIEW, 1108 Uri.parse(uri)).setComponent(compName); 1109 mapsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); 1110 activity.startActivity(mapsIntent); 1111 } catch (ActivityNotFoundException e) { 1112 // Use the "geo intent" if no GMM is installed 1113 Log.e(TAG, "GMM activity not found!", e); 1114 String url = String.format(Locale.ENGLISH, "geo:%f,%f", latLong[0], latLong[1]); 1115 Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 1116 activity.startActivity(mapsIntent); 1117 } 1118 } 1119 1120 /** 1121 * Dumps the stack trace. 1122 * 1123 * @param level How many levels of the stack are dumped. 0 means all. 1124 * @return A {@link java.lang.String} of all the output with newline between 1125 * each. 1126 */ 1127 public static String dumpStackTrace(int level) { 1128 StackTraceElement[] elems = Thread.currentThread().getStackTrace(); 1129 // Ignore the first 3 elements. 1130 level = (level == 0 ? elems.length : Math.min(level + 3, elems.length)); 1131 String ret = new String(); 1132 for (int i = 3; i < level; i++) { 1133 ret = ret + "\t" + elems[i].toString() + '\n'; 1134 } 1135 return ret; 1136 } 1137 1138 /** 1139 * Gets the theme color of a specific mode. 1140 * 1141 * @param modeIndex index of the mode 1142 * @param context current context 1143 * @return theme color of the mode if input index is valid, otherwise 0 1144 */ 1145 public static int getCameraThemeColorId(int modeIndex, Context context) { 1146 1147 // Find the theme color using id from the color array 1148 TypedArray colorRes = context.getResources() 1149 .obtainTypedArray(R.array.camera_mode_theme_color); 1150 if (modeIndex >= colorRes.length() || modeIndex < 0) { 1151 // Mode index not found 1152 Log.e(TAG, "Invalid mode index: " + modeIndex); 1153 return 0; 1154 } 1155 return colorRes.getResourceId(modeIndex, 0); 1156 } 1157 1158 /** 1159 * Gets the mode icon resource id of a specific mode. 1160 * 1161 * @param modeIndex index of the mode 1162 * @param context current context 1163 * @return icon resource id if the index is valid, otherwise 0 1164 */ 1165 public static int getCameraModeIconResId(int modeIndex, Context context) { 1166 // Find the camera mode icon using id 1167 TypedArray cameraModesIcons = context.getResources() 1168 .obtainTypedArray(R.array.camera_mode_icon); 1169 if (modeIndex >= cameraModesIcons.length() || modeIndex < 0) { 1170 // Mode index not found 1171 Log.e(TAG, "Invalid mode index: " + modeIndex); 1172 return 0; 1173 } 1174 return cameraModesIcons.getResourceId(modeIndex, 0); 1175 } 1176 1177 /** 1178 * Gets the mode text of a specific mode. 1179 * 1180 * @param modeIndex index of the mode 1181 * @param context current context 1182 * @return mode text if the index is valid, otherwise a new empty string 1183 */ 1184 public static String getCameraModeText(int modeIndex, Context context) { 1185 // Find the camera mode icon using id 1186 String[] cameraModesText = context.getResources() 1187 .getStringArray(R.array.camera_mode_text); 1188 if (modeIndex < 0 || modeIndex >= cameraModesText.length) { 1189 Log.e(TAG, "Invalid mode index: " + modeIndex); 1190 return new String(); 1191 } 1192 return cameraModesText[modeIndex]; 1193 } 1194 1195 /** 1196 * Gets the mode content description of a specific mode. 1197 * 1198 * @param modeIndex index of the mode 1199 * @param context current context 1200 * @return mode content description if the index is valid, otherwise a new 1201 * empty string 1202 */ 1203 public static String getCameraModeContentDescription(int modeIndex, Context context) { 1204 String[] cameraModesDesc = context.getResources() 1205 .getStringArray(R.array.camera_mode_content_description); 1206 if (modeIndex < 0 || modeIndex >= cameraModesDesc.length) { 1207 Log.e(TAG, "Invalid mode index: " + modeIndex); 1208 return new String(); 1209 } 1210 return cameraModesDesc[modeIndex]; 1211 } 1212 1213 /** 1214 * Gets the shutter icon res id for a specific mode. 1215 * 1216 * @param modeIndex index of the mode 1217 * @param context current context 1218 * @return mode shutter icon id if the index is valid, otherwise 0. 1219 */ 1220 public static int getCameraShutterIconId(int modeIndex, Context context) { 1221 // Find the camera mode icon using id 1222 TypedArray shutterIcons = context.getResources() 1223 .obtainTypedArray(R.array.camera_mode_shutter_icon); 1224 if (modeIndex < 0 || modeIndex >= shutterIcons.length()) { 1225 Log.e(TAG, "Invalid mode index: " + modeIndex); 1226 throw new IllegalStateException("Invalid mode index: " + modeIndex); 1227 } 1228 return shutterIcons.getResourceId(modeIndex, 0); 1229 } 1230 1231 /** 1232 * Gets the parent mode that hosts a specific mode in nav drawer. 1233 * 1234 * @param modeIndex index of the mode 1235 * @param context current context 1236 * @return mode id if the index is valid, otherwise 0 1237 */ 1238 public static int getCameraModeParentModeId(int modeIndex, Context context) { 1239 // Find the camera mode icon using id 1240 int[] cameraModeParent = context.getResources() 1241 .getIntArray(R.array.camera_mode_nested_in_nav_drawer); 1242 if (modeIndex < 0 || modeIndex >= cameraModeParent.length) { 1243 Log.e(TAG, "Invalid mode index: " + modeIndex); 1244 return 0; 1245 } 1246 return cameraModeParent[modeIndex]; 1247 } 1248 1249 /** 1250 * Gets the mode cover icon resource id of a specific mode. 1251 * 1252 * @param modeIndex index of the mode 1253 * @param context current context 1254 * @return icon resource id if the index is valid, otherwise 0 1255 */ 1256 public static int getCameraModeCoverIconResId(int modeIndex, Context context) { 1257 // Find the camera mode icon using id 1258 TypedArray cameraModesIcons = context.getResources() 1259 .obtainTypedArray(R.array.camera_mode_cover_icon); 1260 if (modeIndex >= cameraModesIcons.length() || modeIndex < 0) { 1261 // Mode index not found 1262 Log.e(TAG, "Invalid mode index: " + modeIndex); 1263 return 0; 1264 } 1265 return cameraModesIcons.getResourceId(modeIndex, 0); 1266 } 1267 1268 /** 1269 * Gets the number of cores available in this device, across all processors. 1270 * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu" 1271 * <p> 1272 * Source: http://stackoverflow.com/questions/7962155/ 1273 * 1274 * @return The number of cores, or 1 if failed to get result 1275 */ 1276 public static int getNumCpuCores() { 1277 // Private Class to display only CPU devices in the directory listing 1278 class CpuFilter implements java.io.FileFilter { 1279 @Override 1280 public boolean accept(java.io.File pathname) { 1281 // Check if filename is "cpu", followed by a single digit number 1282 if (java.util.regex.Pattern.matches("cpu[0-9]+", pathname.getName())) { 1283 return true; 1284 } 1285 return false; 1286 } 1287 } 1288 1289 try { 1290 // Get directory containing CPU info 1291 java.io.File dir = new java.io.File("/sys/devices/system/cpu/"); 1292 // Filter to only list the devices we care about 1293 java.io.File[] files = dir.listFiles(new CpuFilter()); 1294 // Return the number of cores (virtual CPU devices) 1295 return files.length; 1296 } catch (Exception e) { 1297 // Default to return 1 core 1298 Log.e(TAG, "Failed to count number of cores, defaulting to 1", e); 1299 return 1; 1300 } 1301 } 1302 1303 /** 1304 * Given the device orientation and Camera2 characteristics, this returns 1305 * the required JPEG rotation for this camera. 1306 * 1307 * @param deviceOrientationDegrees the clockwise angle of the device orientation from its 1308 * natural orientation in degrees. 1309 * @return The angle to rotate image clockwise in degrees. It should be 0, 90, 180, or 270. 1310 */ 1311 public static int getJpegRotation(int deviceOrientationDegrees, 1312 CameraCharacteristics characteristics) { 1313 if (deviceOrientationDegrees == OrientationEventListener.ORIENTATION_UNKNOWN) { 1314 return 0; 1315 } 1316 boolean isFrontCamera = characteristics.get(CameraCharacteristics.LENS_FACING) == 1317 CameraMetadata.LENS_FACING_FRONT; 1318 int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); 1319 return getImageRotation(sensorOrientation, deviceOrientationDegrees, isFrontCamera); 1320 } 1321 1322 /** 1323 * Given the camera sensor orientation and device orientation, this returns a clockwise angle 1324 * which the final image needs to be rotated to be upright on the device screen. 1325 * 1326 * @param sensorOrientation Clockwise angle through which the output image needs to be rotated 1327 * to be upright on the device screen in its native orientation. 1328 * @param deviceOrientation Clockwise angle of the device orientation from its 1329 * native orientation when front camera faces user. 1330 * @param isFrontCamera True if the camera is front-facing. 1331 * @return The angle to rotate image clockwise in degrees. It should be 0, 90, 180, or 270. 1332 */ 1333 public static int getImageRotation(int sensorOrientation, 1334 int deviceOrientation, 1335 boolean isFrontCamera) { 1336 // The sensor of front camera faces in the opposite direction from back camera. 1337 if (isFrontCamera) { 1338 deviceOrientation = (360 - deviceOrientation) % 360; 1339 } 1340 return (sensorOrientation + deviceOrientation) % 360; 1341 } 1342} 1343