Util.java revision 6bca5289166b1444f4b98538343a24d35f46dda5
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; 18 19import android.app.Activity; 20import android.app.AlertDialog; 21import android.content.Context; 22import android.content.DialogInterface; 23import android.graphics.Bitmap; 24import android.graphics.BitmapFactory; 25import android.graphics.Matrix; 26import android.hardware.Camera; 27import android.hardware.Camera.Parameters; 28import android.hardware.Camera.Size; 29import android.telephony.TelephonyManager; 30import android.util.Log; 31import android.view.Display; 32import android.view.Surface; 33import android.view.View; 34import android.view.animation.Animation; 35import android.view.animation.TranslateAnimation; 36 37import java.io.Closeable; 38import java.lang.reflect.Method; 39import java.util.List; 40import java.util.StringTokenizer; 41 42/** 43 * Collection of utility functions used in this package. 44 */ 45public class Util { 46 private static final String TAG = "Util"; 47 public static final int DIRECTION_LEFT = 0; 48 public static final int DIRECTION_RIGHT = 1; 49 public static final int DIRECTION_UP = 2; 50 public static final int DIRECTION_DOWN = 3; 51 52 public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW"; 53 54 private Util() { 55 } 56 57 // Rotates the bitmap by the specified degree. 58 // If a new bitmap is created, the original bitmap is recycled. 59 public static Bitmap rotate(Bitmap b, int degrees) { 60 return rotateAndMirror(b, degrees, false); 61 } 62 63 // Rotates and/or mirrors the bitmap. If a new bitmap is created, the 64 // original bitmap is recycled. 65 public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) { 66 if ((degrees != 0 || mirror) && b != null) { 67 Matrix m = new Matrix(); 68 m.setRotate(degrees, 69 (float) b.getWidth() / 2, (float) b.getHeight() / 2); 70 if (mirror) { 71 m.postScale(-1, 1); 72 degrees = (degrees + 360) % 360; 73 if (degrees == 0 || degrees == 180) { 74 m.postTranslate((float) b.getWidth(), 0); 75 } else if (degrees == 90 || degrees == 270) { 76 m.postTranslate((float) b.getHeight(), 0); 77 } else { 78 throw new IllegalArgumentException("Invalid degrees=" + degrees); 79 } 80 } 81 82 try { 83 Bitmap b2 = Bitmap.createBitmap( 84 b, 0, 0, b.getWidth(), b.getHeight(), m, true); 85 if (b != b2) { 86 b.recycle(); 87 b = b2; 88 } 89 } catch (OutOfMemoryError ex) { 90 // We have no memory to rotate. Return the original bitmap. 91 } 92 } 93 return b; 94 } 95 96 /* 97 * Compute the sample size as a function of minSideLength 98 * and maxNumOfPixels. 99 * minSideLength is used to specify that minimal width or height of a 100 * bitmap. 101 * maxNumOfPixels is used to specify the maximal size in pixels that is 102 * tolerable in terms of memory usage. 103 * 104 * The function returns a sample size based on the constraints. 105 * Both size and minSideLength can be passed in as -1 106 * which indicates no care of the corresponding constraint. 107 * The functions prefers returning a sample size that 108 * generates a smaller bitmap, unless minSideLength = -1. 109 * 110 * Also, the function rounds up the sample size to a power of 2 or multiple 111 * of 8 because BitmapFactory only honors sample size this way. 112 * For example, BitmapFactory downsamples an image by 2 even though the 113 * request is 3. So we round up the sample size to avoid OOM. 114 */ 115 public static int computeSampleSize(BitmapFactory.Options options, 116 int minSideLength, int maxNumOfPixels) { 117 int initialSize = computeInitialSampleSize(options, minSideLength, 118 maxNumOfPixels); 119 120 int roundedSize; 121 if (initialSize <= 8) { 122 roundedSize = 1; 123 while (roundedSize < initialSize) { 124 roundedSize <<= 1; 125 } 126 } else { 127 roundedSize = (initialSize + 7) / 8 * 8; 128 } 129 130 return roundedSize; 131 } 132 133 private static int computeInitialSampleSize(BitmapFactory.Options options, 134 int minSideLength, int maxNumOfPixels) { 135 double w = options.outWidth; 136 double h = options.outHeight; 137 138 int lowerBound = (maxNumOfPixels < 0) ? 1 : 139 (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); 140 int upperBound = (minSideLength < 0) ? 128 : 141 (int) Math.min(Math.floor(w / minSideLength), 142 Math.floor(h / minSideLength)); 143 144 if (upperBound < lowerBound) { 145 // return the larger one when there is no overlapping zone. 146 return lowerBound; 147 } 148 149 if (maxNumOfPixels < 0 && minSideLength < 0) { 150 return 1; 151 } else if (minSideLength < 0) { 152 return lowerBound; 153 } else { 154 return upperBound; 155 } 156 } 157 158 public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) { 159 try { 160 BitmapFactory.Options options = new BitmapFactory.Options(); 161 options.inJustDecodeBounds = true; 162 BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 163 options); 164 if (options.mCancel || options.outWidth == -1 165 || options.outHeight == -1) { 166 return null; 167 } 168 options.inSampleSize = computeSampleSize( 169 options, -1, maxNumOfPixels); 170 options.inJustDecodeBounds = false; 171 172 options.inDither = false; 173 options.inPreferredConfig = Bitmap.Config.ARGB_8888; 174 return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 175 options); 176 } catch (OutOfMemoryError ex) { 177 Log.e(TAG, "Got oom exception ", ex); 178 return null; 179 } 180 } 181 182 public static void closeSilently(Closeable c) { 183 if (c == null) return; 184 try { 185 c.close(); 186 } catch (Throwable t) { 187 // do nothing 188 } 189 } 190 191 public static void Assert(boolean cond) { 192 if (!cond) { 193 throw new AssertionError(); 194 } 195 } 196 197 public static void showFatalErrorAndFinish( 198 final Activity activity, String title, String message) { 199 DialogInterface.OnClickListener buttonListener = 200 new DialogInterface.OnClickListener() { 201 public void onClick(DialogInterface dialog, int which) { 202 activity.finish(); 203 } 204 }; 205 new AlertDialog.Builder(activity) 206 .setCancelable(false) 207 .setIcon(android.R.drawable.ic_dialog_alert) 208 .setTitle(title) 209 .setMessage(message) 210 .setNeutralButton(R.string.details_ok, buttonListener) 211 .show(); 212 } 213 214 public static Animation slideOut(View view, int to) { 215 view.setVisibility(View.INVISIBLE); 216 Animation anim; 217 switch (to) { 218 case DIRECTION_LEFT: 219 anim = new TranslateAnimation(0, -view.getWidth(), 0, 0); 220 break; 221 case DIRECTION_RIGHT: 222 anim = new TranslateAnimation(0, view.getWidth(), 0, 0); 223 break; 224 case DIRECTION_UP: 225 anim = new TranslateAnimation(0, 0, 0, -view.getHeight()); 226 break; 227 case DIRECTION_DOWN: 228 anim = new TranslateAnimation(0, 0, 0, view.getHeight()); 229 break; 230 default: 231 throw new IllegalArgumentException(Integer.toString(to)); 232 } 233 anim.setDuration(500); 234 view.startAnimation(anim); 235 return anim; 236 } 237 238 public static Animation slideIn(View view, int from) { 239 view.setVisibility(View.VISIBLE); 240 Animation anim; 241 switch (from) { 242 case DIRECTION_LEFT: 243 anim = new TranslateAnimation(-view.getWidth(), 0, 0, 0); 244 break; 245 case DIRECTION_RIGHT: 246 anim = new TranslateAnimation(view.getWidth(), 0, 0, 0); 247 break; 248 case DIRECTION_UP: 249 anim = new TranslateAnimation(0, 0, -view.getHeight(), 0); 250 break; 251 case DIRECTION_DOWN: 252 anim = new TranslateAnimation(0, 0, view.getHeight(), 0); 253 break; 254 default: 255 throw new IllegalArgumentException(Integer.toString(from)); 256 } 257 anim.setDuration(500); 258 view.startAnimation(anim); 259 return anim; 260 } 261 262 public static <T> T checkNotNull(T object) { 263 if (object == null) throw new NullPointerException(); 264 return object; 265 } 266 267 public static boolean equals(Object a, Object b) { 268 return (a == b) || (a == null ? false : a.equals(b)); 269 } 270 271 public static boolean isPowerOf2(int n) { 272 return (n & -n) == n; 273 } 274 275 public static int nextPowerOf2(int n) { 276 n -= 1; 277 n |= n >>> 16; 278 n |= n >>> 8; 279 n |= n >>> 4; 280 n |= n >>> 2; 281 n |= n >>> 1; 282 return n + 1; 283 } 284 285 public static float distance(float x, float y, float sx, float sy) { 286 float dx = x - sx; 287 float dy = y - sy; 288 return (float) Math.sqrt(dx * dx + dy * dy); 289 } 290 291 public static int clamp(int x, int min, int max) { 292 if (x > max) return max; 293 if (x < min) return min; 294 return x; 295 } 296 297 public static int getDisplayRotation(Activity activity) { 298 int rotation = activity.getWindowManager().getDefaultDisplay() 299 .getRotation(); 300 switch (rotation) { 301 case Surface.ROTATION_0: return 0; 302 case Surface.ROTATION_90: return 90; 303 case Surface.ROTATION_180: return 180; 304 case Surface.ROTATION_270: return 270; 305 } 306 return 0; 307 } 308 309 public static void setCameraDisplayOrientation(Activity activity, 310 int cameraId, Camera camera) { 311 // See android.hardware.Camera.setCameraDisplayOrientation for 312 // documentation. 313 Camera.CameraInfo info = new Camera.CameraInfo(); 314 Camera.getCameraInfo(cameraId, info); 315 int degrees = getDisplayRotation(activity); 316 int result; 317 if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { 318 result = (info.orientation + degrees) % 360; 319 result = (360 - result) % 360; // compensate the mirror 320 } else { // back-facing 321 result = (info.orientation - degrees + 360) % 360; 322 } 323 camera.setDisplayOrientation(result); 324 } 325 326 public static Size getOptimalPreviewSize(Activity currentActivity, 327 List<Size> sizes, double targetRatio) { 328 // Use a very small tolerance because we want an exact match. 329 final double ASPECT_TOLERANCE = 0.001; 330 if (sizes == null) return null; 331 332 Size optimalSize = null; 333 double minDiff = Double.MAX_VALUE; 334 335 // Because of bugs of overlay and layout, we sometimes will try to 336 // layout the viewfinder in the portrait orientation and thus get the 337 // wrong size of mSurfaceView. When we change the preview size, the 338 // new overlay will be created before the old one closed, which causes 339 // an exception. For now, just get the screen size 340 341 Display display = currentActivity.getWindowManager().getDefaultDisplay(); 342 int targetHeight = Math.min(display.getHeight(), display.getWidth()); 343 344 if (targetHeight <= 0) { 345 // We don't know the size of SurfaceView, use screen height 346 targetHeight = display.getHeight(); 347 } 348 349 // Try to find an size match aspect ratio and size 350 for (Size size : sizes) { 351 double ratio = (double) size.width / size.height; 352 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; 353 if (Math.abs(size.height - targetHeight) < minDiff) { 354 optimalSize = size; 355 minDiff = Math.abs(size.height - targetHeight); 356 } 357 } 358 359 // Cannot find the one match the aspect ratio. This should not happen. 360 // Ignore the requirement. 361 if (optimalSize == null) { 362 Log.w(TAG, "No preview size match the aspect ratio"); 363 minDiff = Double.MAX_VALUE; 364 for (Size size : sizes) { 365 if (Math.abs(size.height - targetHeight) < minDiff) { 366 optimalSize = size; 367 minDiff = Math.abs(size.height - targetHeight); 368 } 369 } 370 } 371 return optimalSize; 372 } 373 374 public static void dumpParameters(Parameters parameters) { 375 String flattened = parameters.flatten(); 376 StringTokenizer tokenizer = new StringTokenizer(flattened, ";"); 377 Log.d(TAG, "Dump all camera parameters:"); 378 while (tokenizer.hasMoreElements()) { 379 Log.d(TAG, tokenizer.nextToken()); 380 } 381 } 382 383 /** 384 * Returns whether the device is voice-capable (meaning, it can do MMS). 385 */ 386 public static boolean isMmsCapable(Context context) { 387 TelephonyManager telephonyManager = (TelephonyManager) 388 context.getSystemService(Context.TELEPHONY_SERVICE); 389 if (telephonyManager == null) { 390 return false; 391 } 392 393 try { 394 Class partypes[] = new Class[0]; 395 Method sIsVoiceCapable = TelephonyManager.class.getMethod( 396 "isVoiceCapable", partypes); 397 398 Object arglist[] = new Object[0]; 399 Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist); 400 return (Boolean) retobj; 401 } catch (java.lang.reflect.InvocationTargetException ite) { 402 // Failure, must be another device. 403 // Assume that it is voice capable. 404 } catch (java.lang.IllegalAccessException iae) { 405 // Failure, must be an other device. 406 // Assume that it is voice capable. 407 } catch (NoSuchMethodException nsme) { 408 } 409 return true; 410 } 411} 412