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