Util.java revision cd972b0cd67d7a45084d9757ebd49b8f22989edd
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.app.ProgressDialog; 22import android.content.ContentResolver; 23import android.content.DialogInterface; 24import android.content.Intent; 25import android.graphics.Bitmap; 26import android.graphics.BitmapFactory; 27import android.graphics.Canvas; 28import android.graphics.Matrix; 29import android.graphics.Rect; 30import android.media.MediaMetadataRetriever; 31import android.net.Uri; 32import android.os.Handler; 33import android.os.ParcelFileDescriptor; 34import android.util.Log; 35import android.view.View; 36import android.view.View.OnClickListener; 37import android.view.animation.Animation; 38import android.view.animation.TranslateAnimation; 39 40import com.android.camera.gallery.IImage; 41 42import java.io.ByteArrayOutputStream; 43import java.io.Closeable; 44import java.io.FileDescriptor; 45import java.io.IOException; 46 47/** 48 * Collection of utility functions used in this package. 49 */ 50public class Util { 51 private static final String TAG = "Util"; 52 public static final int DIRECTION_LEFT = 0; 53 public static final int DIRECTION_RIGHT = 1; 54 public static final int DIRECTION_UP = 2; 55 public static final int DIRECTION_DOWN = 3; 56 57 private static OnClickListener sNullOnClickListener; 58 59 private Util() { 60 } 61 62 // Rotates the bitmap by the specified degree. 63 // If a new bitmap is created, the original bitmap is recycled. 64 public static Bitmap rotate(Bitmap b, int degrees) { 65 if (degrees != 0 && b != null) { 66 Matrix m = new Matrix(); 67 m.setRotate(degrees, 68 (float) b.getWidth() / 2, (float) b.getHeight() / 2); 69 try { 70 Bitmap b2 = Bitmap.createBitmap( 71 b, 0, 0, b.getWidth(), b.getHeight(), m, true); 72 if (b != b2) { 73 b.recycle(); 74 b = b2; 75 } 76 } catch (OutOfMemoryError ex) { 77 // We have no memory to rotate. Return the original bitmap. 78 } 79 } 80 return b; 81 } 82 83 /* 84 * Compute the sample size as a function of minSideLength 85 * and maxNumOfPixels. 86 * minSideLength is used to specify that minimal width or height of a 87 * bitmap. 88 * maxNumOfPixels is used to specify the maximal size in pixels that is 89 * tolerable in terms of memory usage. 90 * 91 * The function returns a sample size based on the constraints. 92 * Both size and minSideLength can be passed in as IImage.UNCONSTRAINED, 93 * which indicates no care of the corresponding constraint. 94 * The functions prefers returning a sample size that 95 * generates a smaller bitmap, unless minSideLength = IImage.UNCONSTRAINED. 96 * 97 * Also, the function rounds up the sample size to a power of 2 or multiple 98 * of 8 because BitmapFactory only honors sample size this way. 99 * For example, BitmapFactory downsamples an image by 2 even though the 100 * request is 3. So we round up the sample size to avoid OOM. 101 */ 102 public static int computeSampleSize(BitmapFactory.Options options, 103 int minSideLength, int maxNumOfPixels) { 104 int initialSize = computeInitialSampleSize(options, minSideLength, 105 maxNumOfPixels); 106 107 int roundedSize; 108 if (initialSize <= 8) { 109 roundedSize = 1; 110 while (roundedSize < initialSize) { 111 roundedSize <<= 1; 112 } 113 } else { 114 roundedSize = (initialSize + 7) / 8 * 8; 115 } 116 117 return roundedSize; 118 } 119 120 private static int computeInitialSampleSize(BitmapFactory.Options options, 121 int minSideLength, int maxNumOfPixels) { 122 double w = options.outWidth; 123 double h = options.outHeight; 124 125 int lowerBound = (maxNumOfPixels == IImage.UNCONSTRAINED) ? 1 : 126 (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); 127 int upperBound = (minSideLength == IImage.UNCONSTRAINED) ? 128 : 128 (int) Math.min(Math.floor(w / minSideLength), 129 Math.floor(h / minSideLength)); 130 131 if (upperBound < lowerBound) { 132 // return the larger one when there is no overlapping zone. 133 return lowerBound; 134 } 135 136 if ((maxNumOfPixels == IImage.UNCONSTRAINED) && 137 (minSideLength == IImage.UNCONSTRAINED)) { 138 return 1; 139 } else if (minSideLength == IImage.UNCONSTRAINED) { 140 return lowerBound; 141 } else { 142 return upperBound; 143 } 144 } 145 146 // Whether we should recycle the input (unless the output is the input). 147 public static final boolean RECYCLE_INPUT = true; 148 public static final boolean NO_RECYCLE_INPUT = false; 149 150 public static Bitmap transform(Matrix scaler, 151 Bitmap source, 152 int targetWidth, 153 int targetHeight, 154 boolean scaleUp, 155 boolean recycle) { 156 int deltaX = source.getWidth() - targetWidth; 157 int deltaY = source.getHeight() - targetHeight; 158 if (!scaleUp && (deltaX < 0 || deltaY < 0)) { 159 /* 160 * In this case the bitmap is smaller, at least in one dimension, 161 * than the target. Transform it by placing as much of the image 162 * as possible into the target and leaving the top/bottom or 163 * left/right (or both) black. 164 */ 165 Bitmap b2 = Bitmap.createBitmap(targetWidth, targetHeight, 166 Bitmap.Config.ARGB_8888); 167 Canvas c = new Canvas(b2); 168 169 int deltaXHalf = Math.max(0, deltaX / 2); 170 int deltaYHalf = Math.max(0, deltaY / 2); 171 Rect src = new Rect( 172 deltaXHalf, 173 deltaYHalf, 174 deltaXHalf + Math.min(targetWidth, source.getWidth()), 175 deltaYHalf + Math.min(targetHeight, source.getHeight())); 176 int dstX = (targetWidth - src.width()) / 2; 177 int dstY = (targetHeight - src.height()) / 2; 178 Rect dst = new Rect( 179 dstX, 180 dstY, 181 targetWidth - dstX, 182 targetHeight - dstY); 183 c.drawBitmap(source, src, dst, null); 184 if (recycle) { 185 source.recycle(); 186 } 187 return b2; 188 } 189 float bitmapWidthF = source.getWidth(); 190 float bitmapHeightF = source.getHeight(); 191 192 float bitmapAspect = bitmapWidthF / bitmapHeightF; 193 float viewAspect = (float) targetWidth / targetHeight; 194 195 if (bitmapAspect > viewAspect) { 196 float scale = targetHeight / bitmapHeightF; 197 if (scale < .9F || scale > 1F) { 198 scaler.setScale(scale, scale); 199 } else { 200 scaler = null; 201 } 202 } else { 203 float scale = targetWidth / bitmapWidthF; 204 if (scale < .9F || scale > 1F) { 205 scaler.setScale(scale, scale); 206 } else { 207 scaler = null; 208 } 209 } 210 211 Bitmap b1; 212 if (scaler != null) { 213 // this is used for minithumb and crop, so we want to filter here. 214 b1 = Bitmap.createBitmap(source, 0, 0, 215 source.getWidth(), source.getHeight(), scaler, true); 216 } else { 217 b1 = source; 218 } 219 220 if (recycle && b1 != source) { 221 source.recycle(); 222 } 223 224 int dx1 = Math.max(0, b1.getWidth() - targetWidth); 225 int dy1 = Math.max(0, b1.getHeight() - targetHeight); 226 227 Bitmap b2 = Bitmap.createBitmap( 228 b1, 229 dx1 / 2, 230 dy1 / 2, 231 targetWidth, 232 targetHeight); 233 234 if (b2 != b1) { 235 if (recycle || b1 != source) { 236 b1.recycle(); 237 } 238 } 239 240 return b2; 241 } 242 243 /** 244 * Creates a centered bitmap of the desired size. 245 * @param source 246 * @param recycle whether we want to recycle the input 247 */ 248 public static Bitmap extractMiniThumb( 249 Bitmap source, int width, int height, boolean recycle) { 250 if (source == null) { 251 return null; 252 } 253 254 float scale; 255 if (source.getWidth() < source.getHeight()) { 256 scale = width / (float) source.getWidth(); 257 } else { 258 scale = height / (float) source.getHeight(); 259 } 260 Matrix matrix = new Matrix(); 261 matrix.setScale(scale, scale); 262 Bitmap miniThumbnail = transform(matrix, source, width, height, 263 true, recycle); 264 return miniThumbnail; 265 } 266 267 /** 268 * Creates a byte[] for a given bitmap of the desired size. Recycles the 269 * input bitmap. 270 */ 271 public static byte[] miniThumbData(Bitmap source) { 272 if (source == null) return null; 273 274 Bitmap miniThumbnail = extractMiniThumb( 275 source, IImage.MINI_THUMB_TARGET_SIZE, 276 IImage.MINI_THUMB_TARGET_SIZE, 277 Util.RECYCLE_INPUT); 278 279 ByteArrayOutputStream miniOutStream = new ByteArrayOutputStream(); 280 miniThumbnail.compress(Bitmap.CompressFormat.JPEG, 75, miniOutStream); 281 miniThumbnail.recycle(); 282 283 try { 284 miniOutStream.close(); 285 byte [] data = miniOutStream.toByteArray(); 286 return data; 287 } catch (java.io.IOException ex) { 288 Log.e(TAG, "got exception ex " + ex); 289 } 290 return null; 291 } 292 293 /** 294 * Create a video thumbnail for a video. May return null if the video is 295 * corrupt. 296 * 297 * @param filePath 298 */ 299 public static Bitmap createVideoThumbnail(String filePath) { 300 Bitmap bitmap = null; 301 MediaMetadataRetriever retriever = new MediaMetadataRetriever(); 302 try { 303 retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY); 304 retriever.setDataSource(filePath); 305 bitmap = retriever.captureFrame(); 306 } catch (IllegalArgumentException ex) { 307 // Assume this is a corrupt video file 308 } catch (RuntimeException ex) { 309 // Assume this is a corrupt video file. 310 } finally { 311 try { 312 retriever.release(); 313 } catch (RuntimeException ex) { 314 // Ignore failures while cleaning up. 315 } 316 } 317 return bitmap; 318 } 319 320 public static <T> int indexOf(T [] array, T s) { 321 for (int i = 0; i < array.length; i++) { 322 if (array[i].equals(s)) { 323 return i; 324 } 325 } 326 return -1; 327 } 328 329 public static void closeSilently(Closeable c) { 330 if (c == null) return; 331 try { 332 c.close(); 333 } catch (Throwable t) { 334 // do nothing 335 } 336 } 337 338 public static void closeSilently(ParcelFileDescriptor c) { 339 if (c == null) return; 340 try { 341 c.close(); 342 } catch (Throwable t) { 343 // do nothing 344 } 345 } 346 347 /** 348 * Make a bitmap from a given Uri. 349 * 350 * @param uri 351 */ 352 public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels, 353 Uri uri, ContentResolver cr) { 354 return makeBitmap(minSideLength, maxNumOfPixels, uri, cr, 355 IImage.NO_NATIVE); 356 } 357 358 public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels, 359 Uri uri, ContentResolver cr, boolean useNative) { 360 ParcelFileDescriptor input = null; 361 try { 362 input = cr.openFileDescriptor(uri, "r"); 363 BitmapFactory.Options options = null; 364 if (useNative) { 365 options = createNativeAllocOptions(); 366 } 367 return makeBitmap(minSideLength, maxNumOfPixels, uri, cr, input, 368 options); 369 } catch (IOException ex) { 370 return null; 371 } finally { 372 closeSilently(input); 373 } 374 } 375 376 public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels, 377 ParcelFileDescriptor pfd, boolean useNative) { 378 BitmapFactory.Options options = null; 379 if (useNative) { 380 options = createNativeAllocOptions(); 381 } 382 return makeBitmap(minSideLength, maxNumOfPixels, null, null, pfd, 383 options); 384 } 385 386 public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels, 387 Uri uri, ContentResolver cr, ParcelFileDescriptor pfd, 388 BitmapFactory.Options options) { 389 try { 390 if (pfd == null) pfd = makeInputStream(uri, cr); 391 if (pfd == null) return null; 392 if (options == null) options = new BitmapFactory.Options(); 393 394 FileDescriptor fd = pfd.getFileDescriptor(); 395 options.inJustDecodeBounds = true; 396 BitmapManager.instance().decodeFileDescriptor(fd, options); 397 if (options.mCancel || options.outWidth == -1 398 || options.outHeight == -1) { 399 return null; 400 } 401 options.inSampleSize = computeSampleSize( 402 options, minSideLength, maxNumOfPixels); 403 options.inJustDecodeBounds = false; 404 405 options.inDither = false; 406 options.inPreferredConfig = Bitmap.Config.ARGB_8888; 407 return BitmapManager.instance().decodeFileDescriptor(fd, options); 408 } catch (OutOfMemoryError ex) { 409 Log.e(TAG, "Got oom exception ", ex); 410 return null; 411 } finally { 412 closeSilently(pfd); 413 } 414 } 415 416 public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) { 417 try { 418 BitmapFactory.Options options = new BitmapFactory.Options(); 419 options.inJustDecodeBounds = true; 420 BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 421 options); 422 if (options.mCancel || options.outWidth == -1 423 || options.outHeight == -1) { 424 return null; 425 } 426 options.inSampleSize = computeSampleSize( 427 options, IImage.UNCONSTRAINED, maxNumOfPixels); 428 options.inJustDecodeBounds = false; 429 430 options.inDither = false; 431 options.inPreferredConfig = Bitmap.Config.ARGB_8888; 432 return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, 433 options); 434 } catch (OutOfMemoryError ex) { 435 Log.e(TAG, "Got oom exception ", ex); 436 return null; 437 } 438 } 439 440 private static ParcelFileDescriptor makeInputStream( 441 Uri uri, ContentResolver cr) { 442 try { 443 return cr.openFileDescriptor(uri, "r"); 444 } catch (IOException ex) { 445 return null; 446 } 447 } 448 449 public static synchronized OnClickListener getNullOnClickListener() { 450 if (sNullOnClickListener == null) { 451 sNullOnClickListener = new OnClickListener() { 452 public void onClick(View v) { 453 } 454 }; 455 } 456 return sNullOnClickListener; 457 } 458 459 public static void Assert(boolean cond) { 460 if (!cond) { 461 throw new AssertionError(); 462 } 463 } 464 465 public static boolean equals(String a, String b) { 466 // return true if both string are null or the content equals 467 return a == b || a.equals(b); 468 } 469 470 private static class BackgroundJob 471 extends MonitoredActivity.LifeCycleAdapter implements Runnable { 472 473 private final MonitoredActivity mActivity; 474 private final ProgressDialog mDialog; 475 private final Runnable mJob; 476 private final Handler mHandler; 477 private final Runnable mCleanupRunner = new Runnable() { 478 public void run() { 479 mActivity.removeLifeCycleListener(BackgroundJob.this); 480 if (mDialog.getWindow() != null) mDialog.dismiss(); 481 } 482 }; 483 484 public BackgroundJob(MonitoredActivity activity, Runnable job, 485 ProgressDialog dialog, Handler handler) { 486 mActivity = activity; 487 mDialog = dialog; 488 mJob = job; 489 mActivity.addLifeCycleListener(this); 490 mHandler = handler; 491 } 492 493 public void run() { 494 try { 495 mJob.run(); 496 } finally { 497 mHandler.post(mCleanupRunner); 498 } 499 } 500 501 502 @Override 503 public void onActivityDestroyed(MonitoredActivity activity) { 504 // We get here only when the onDestroyed being called before 505 // the mCleanupRunner. So, run it now and remove it from the queue 506 mCleanupRunner.run(); 507 mHandler.removeCallbacks(mCleanupRunner); 508 } 509 510 @Override 511 public void onActivityStopped(MonitoredActivity activity) { 512 mDialog.hide(); 513 } 514 515 @Override 516 public void onActivityStarted(MonitoredActivity activity) { 517 mDialog.show(); 518 } 519 } 520 521 public static void startBackgroundJob(MonitoredActivity activity, 522 String title, String message, Runnable job, Handler handler) { 523 // Make the progress dialog uncancelable, so that we can gurantee 524 // the thread will be done before the activity getting destroyed. 525 ProgressDialog dialog = ProgressDialog.show( 526 activity, title, message, true, false); 527 new Thread(new BackgroundJob(activity, job, dialog, handler)).start(); 528 } 529 530 // Returns an intent which is used for "set as" menu items. 531 public static Intent createSetAsIntent(IImage image) { 532 Uri u = image.fullSizeImageUri(); 533 Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); 534 intent.setDataAndType(u, image.getMimeType()); 535 intent.putExtra("mimeType", image.getMimeType()); 536 return intent; 537 } 538 539 // Returns Options that set the puregeable flag for Bitmap decode. 540 public static BitmapFactory.Options createNativeAllocOptions() { 541 BitmapFactory.Options options = new BitmapFactory.Options(); 542 options.inNativeAlloc = true; 543 return options; 544 } 545 546 public static void showFatalErrorAndFinish( 547 final Activity activity, String title, String message) { 548 DialogInterface.OnClickListener buttonListener = 549 new DialogInterface.OnClickListener() { 550 public void onClick(DialogInterface dialog, int which) { 551 activity.finish(); 552 } 553 }; 554 new AlertDialog.Builder(activity) 555 .setCancelable(false) 556 .setIcon(android.R.drawable.ic_dialog_alert) 557 .setTitle(title) 558 .setMessage(message) 559 .setNeutralButton(R.string.details_ok, buttonListener) 560 .show(); 561 } 562 563 public static Animation slideOut(View view, int to) { 564 view.setVisibility(View.INVISIBLE); 565 Animation anim; 566 switch (to) { 567 case DIRECTION_LEFT: 568 anim = new TranslateAnimation(0, -view.getWidth(), 0, 0); 569 break; 570 case DIRECTION_RIGHT: 571 anim = new TranslateAnimation(0, view.getWidth(), 0, 0); 572 break; 573 case DIRECTION_UP: 574 anim = new TranslateAnimation(0, 0, 0, -view.getHeight()); 575 break; 576 case DIRECTION_DOWN: 577 anim = new TranslateAnimation(0, 0, 0, view.getHeight()); 578 break; 579 default: 580 throw new IllegalArgumentException(Integer.toString(to)); 581 } 582 anim.setDuration(500); 583 view.startAnimation(anim); 584 return anim; 585 } 586 587 public static Animation slideIn(View view, int from) { 588 view.setVisibility(View.VISIBLE); 589 Animation anim; 590 switch (from) { 591 case DIRECTION_LEFT: 592 anim = new TranslateAnimation(-view.getWidth(), 0, 0, 0); 593 break; 594 case DIRECTION_RIGHT: 595 anim = new TranslateAnimation(view.getWidth(), 0, 0, 0); 596 break; 597 case DIRECTION_UP: 598 anim = new TranslateAnimation(0, 0, -view.getHeight(), 0); 599 break; 600 case DIRECTION_DOWN: 601 anim = new TranslateAnimation(0, 0, view.getHeight(), 0); 602 break; 603 default: 604 throw new IllegalArgumentException(Integer.toString(from)); 605 } 606 anim.setDuration(500); 607 view.startAnimation(anim); 608 return anim; 609 } 610 611 public static <T> T checkNotNull(T object) { 612 if (object == null) throw new NullPointerException(); 613 return object; 614 } 615} 616