1 /* 2 * Copyright (C) 2011 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 17 package com.android.camera; 18 19 import android.graphics.Bitmap; 20 import android.media.MediaMetadataRetriever; 21 22 import java.io.FileDescriptor; 23 import java.io.IOException; 24 25 public class Thumbnail { createVideoThumbnailBitmap(FileDescriptor fd, int targetWidth)26 public static Bitmap createVideoThumbnailBitmap(FileDescriptor fd, int targetWidth) { 27 return createVideoThumbnailBitmap(null, fd, targetWidth); 28 } 29 createVideoThumbnailBitmap(String filePath, int targetWidth)30 public static Bitmap createVideoThumbnailBitmap(String filePath, int targetWidth) { 31 return createVideoThumbnailBitmap(filePath, null, targetWidth); 32 } 33 createVideoThumbnailBitmap(String filePath, FileDescriptor fd, int targetWidth)34 private static Bitmap createVideoThumbnailBitmap(String filePath, FileDescriptor fd, 35 int targetWidth) { 36 Bitmap bitmap = null; 37 MediaMetadataRetriever retriever = new MediaMetadataRetriever(); 38 try { 39 if (filePath != null) { 40 retriever.setDataSource(filePath); 41 } else { 42 retriever.setDataSource(fd); 43 } 44 bitmap = retriever.getFrameAtTime(-1); 45 } catch (IllegalArgumentException ex) { 46 // Assume this is a corrupt video file 47 } catch (RuntimeException ex) { 48 // Assume this is a corrupt video file. 49 } finally { 50 try { 51 retriever.release(); 52 } catch (RuntimeException | IOException ex) { 53 // Ignore failures while cleaning up. 54 } 55 } 56 if (bitmap == null) return null; 57 58 // Scale down the bitmap if it is bigger than we need. 59 int width = bitmap.getWidth(); 60 int height = bitmap.getHeight(); 61 if (width > targetWidth) { 62 float scale = (float) targetWidth / width; 63 int w = Math.round(scale * width); 64 int h = Math.round(scale * height); 65 bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true); 66 } 67 return bitmap; 68 } 69 } 70