Thumbnail.java revision aef5310d25537494679f9ec6b9d7a1a9cb60887d
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
17package com.android.camera;
18
19import android.content.ContentResolver;
20import android.content.ContentUris;
21import android.database.Cursor;
22import android.graphics.Bitmap;
23import android.graphics.BitmapFactory;
24import android.graphics.Matrix;
25import android.media.MediaMetadataRetriever;
26import android.net.Uri;
27import android.provider.MediaStore.Images;
28import android.provider.MediaStore.Images.ImageColumns;
29import android.provider.MediaStore.MediaColumns;
30import android.provider.MediaStore.Video;
31import android.provider.MediaStore.Video.VideoColumns;
32import android.util.Log;
33
34import java.io.BufferedInputStream;
35import java.io.BufferedOutputStream;
36import java.io.DataInputStream;
37import java.io.DataOutputStream;
38import java.io.File;
39import java.io.FileDescriptor;
40import java.io.FileInputStream;
41import java.io.FileOutputStream;
42import java.io.IOException;
43
44public class Thumbnail {
45    private static final String TAG = "Thumbnail";
46
47    private static final String LAST_THUMB_FILENAME = "last_thumb";
48    private static final int BUFSIZE = 4096;
49
50    private Uri mUri;
51    private Bitmap mBitmap;
52    // whether this thumbnail is read from file
53    private boolean mFromFile = false;
54
55    // Camera, VideoCamera, and Panorama share the same thumbnail. Use sLock
56    // to serialize the storage access.
57    private static Object sLock = new Object();
58
59    private Thumbnail(Uri uri, Bitmap bitmap, int orientation) {
60        mUri = uri;
61        mBitmap = rotateImage(bitmap, orientation);
62    }
63
64    public Uri getUri() {
65        return mUri;
66    }
67
68    public Bitmap getBitmap() {
69        return mBitmap;
70    }
71
72    public void setFromFile(boolean fromFile) {
73        mFromFile = fromFile;
74    }
75
76    public boolean fromFile() {
77        return mFromFile;
78    }
79
80    private static Bitmap rotateImage(Bitmap bitmap, int orientation) {
81        if (orientation != 0) {
82            // We only rotate the thumbnail once even if we get OOM.
83            Matrix m = new Matrix();
84            m.setRotate(orientation, bitmap.getWidth() * 0.5f,
85                    bitmap.getHeight() * 0.5f);
86
87            try {
88                Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0,
89                        bitmap.getWidth(), bitmap.getHeight(), m, true);
90                // If the rotated bitmap is the original bitmap, then it
91                // should not be recycled.
92                if (rotated != bitmap) bitmap.recycle();
93                return rotated;
94            } catch (Throwable t) {
95                Log.w(TAG, "Failed to rotate thumbnail", t);
96            }
97        }
98        return bitmap;
99    }
100
101    // Stores the bitmap to the specified file.
102    public void saveLastThumbnailToFile(File filesDir) {
103        File file = new File(filesDir, LAST_THUMB_FILENAME);
104        FileOutputStream f = null;
105        BufferedOutputStream b = null;
106        DataOutputStream d = null;
107        synchronized (sLock) {
108            try {
109                f = new FileOutputStream(file);
110                b = new BufferedOutputStream(f, BUFSIZE);
111                d = new DataOutputStream(b);
112                d.writeUTF(mUri.toString());
113                mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, d);
114                d.close();
115            } catch (IOException e) {
116                Log.e(TAG, "Fail to store bitmap. path=" + file.getPath(), e);
117            } finally {
118                Util.closeSilently(f);
119                Util.closeSilently(b);
120                Util.closeSilently(d);
121            }
122        }
123    }
124
125    // Loads the data from the specified file.
126    // Returns null if failure or the Uri is invalid.
127    public static Thumbnail getLastThumbnailFromFile(File filesDir, ContentResolver resolver) {
128        File file = new File(filesDir, LAST_THUMB_FILENAME);
129        Uri uri = null;
130        Bitmap bitmap = null;
131        FileInputStream f = null;
132        BufferedInputStream b = null;
133        DataInputStream d = null;
134        synchronized (sLock) {
135            try {
136                f = new FileInputStream(file);
137                b = new BufferedInputStream(f, BUFSIZE);
138                d = new DataInputStream(b);
139                uri = Uri.parse(d.readUTF());
140                if (!Util.isUriValid(uri, resolver)) {
141                    d.close();
142                    return null;
143                }
144                bitmap = BitmapFactory.decodeStream(d);
145                d.close();
146            } catch (IOException e) {
147                Log.i(TAG, "Fail to load bitmap. " + e);
148                return null;
149            } finally {
150                Util.closeSilently(f);
151                Util.closeSilently(b);
152                Util.closeSilently(d);
153            }
154        }
155        Thumbnail thumbnail = createThumbnail(uri, bitmap, 0);
156        if (thumbnail != null) thumbnail.setFromFile(true);
157        return thumbnail;
158    }
159
160    public static Thumbnail getLastThumbnailFromContentResolver(ContentResolver resolver) {
161        Media image = getLastImageThumbnail(resolver);
162        Media video = getLastVideoThumbnail(resolver);
163        if (image == null && video == null) return null;
164
165        Bitmap bitmap = null;
166        Media lastMedia;
167        // If there is only image or video, get its thumbnail. If both exist,
168        // get the thumbnail of the one that is newer.
169        if (image != null && (video == null || image.dateTaken >= video.dateTaken)) {
170            bitmap = Images.Thumbnails.getThumbnail(resolver, image.id,
171                    Images.Thumbnails.MINI_KIND, null);
172            lastMedia = image;
173        } else {
174            bitmap = Video.Thumbnails.getThumbnail(resolver, video.id,
175                    Video.Thumbnails.MINI_KIND, null);
176            lastMedia = video;
177        }
178
179        // Ensure database and storage are in sync.
180        if (Util.isUriValid(lastMedia.uri, resolver)) {
181            return createThumbnail(lastMedia.uri, bitmap, lastMedia.orientation);
182        }
183        return null;
184    }
185
186    private static class Media {
187        public Media(long id, int orientation, long dateTaken, Uri uri) {
188            this.id = id;
189            this.orientation = orientation;
190            this.dateTaken = dateTaken;
191            this.uri = uri;
192        }
193
194        public final long id;
195        public final int orientation;
196        public final long dateTaken;
197        public final Uri uri;
198    }
199
200    private static Media getLastImageThumbnail(ContentResolver resolver) {
201        Uri baseUri = Images.Media.EXTERNAL_CONTENT_URI;
202
203        Uri query = baseUri.buildUpon().appendQueryParameter("limit", "1").build();
204        String[] projection = new String[] {ImageColumns._ID, ImageColumns.ORIENTATION,
205                ImageColumns.DATE_TAKEN};
206        String selection = ImageColumns.MIME_TYPE + "='image/jpeg' AND " +
207                ImageColumns.BUCKET_ID + '=' + Storage.BUCKET_ID;
208        String order = ImageColumns.DATE_TAKEN + " DESC," + ImageColumns._ID + " DESC";
209
210        Cursor cursor = null;
211        try {
212            cursor = resolver.query(query, projection, selection, null, order);
213            if (cursor != null && cursor.moveToFirst()) {
214                long id = cursor.getLong(0);
215                return new Media(id, cursor.getInt(1), cursor.getLong(2),
216                                 ContentUris.withAppendedId(baseUri, id));
217            }
218        } finally {
219            if (cursor != null) {
220                cursor.close();
221            }
222        }
223        return null;
224    }
225
226    private static Media getLastVideoThumbnail(ContentResolver resolver) {
227        Uri baseUri = Video.Media.EXTERNAL_CONTENT_URI;
228
229        Uri query = baseUri.buildUpon().appendQueryParameter("limit", "1").build();
230        String[] projection = new String[] {VideoColumns._ID, MediaColumns.DATA,
231                VideoColumns.DATE_TAKEN};
232        String selection = VideoColumns.BUCKET_ID + '=' + Storage.BUCKET_ID;
233        String order = VideoColumns.DATE_TAKEN + " DESC," + VideoColumns._ID + " DESC";
234
235        Cursor cursor = null;
236        try {
237            cursor = resolver.query(query, projection, selection, null, order);
238            if (cursor != null && cursor.moveToFirst()) {
239                Log.d(TAG, "getLastVideoThumbnail: " + cursor.getString(1));
240                long id = cursor.getLong(0);
241                return new Media(id, 0, cursor.getLong(2),
242                        ContentUris.withAppendedId(baseUri, id));
243            }
244        } finally {
245            if (cursor != null) {
246                cursor.close();
247            }
248        }
249        return null;
250    }
251
252    public static Thumbnail createThumbnail(byte[] jpeg, int orientation, int inSampleSize,
253            Uri uri) {
254        // Create the thumbnail.
255        BitmapFactory.Options options = new BitmapFactory.Options();
256        options.inSampleSize = inSampleSize;
257        Bitmap bitmap = BitmapFactory.decodeByteArray(jpeg, 0, jpeg.length, options);
258        return createThumbnail(uri, bitmap, orientation);
259    }
260
261    public static Bitmap createVideoThumbnailBitmap(FileDescriptor fd, int targetWidth) {
262        return createVideoThumbnailBitmap(null, fd, targetWidth);
263    }
264
265    public static Bitmap createVideoThumbnailBitmap(String filePath, int targetWidth) {
266        return createVideoThumbnailBitmap(filePath, null, targetWidth);
267    }
268
269    private static Bitmap createVideoThumbnailBitmap(String filePath, FileDescriptor fd,
270            int targetWidth) {
271        Bitmap bitmap = null;
272        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
273        try {
274            if (filePath != null) {
275                retriever.setDataSource(filePath);
276            } else {
277                retriever.setDataSource(fd);
278            }
279            bitmap = retriever.getFrameAtTime(-1);
280        } catch (IllegalArgumentException ex) {
281            // Assume this is a corrupt video file
282        } catch (RuntimeException ex) {
283            // Assume this is a corrupt video file.
284        } finally {
285            try {
286                retriever.release();
287            } catch (RuntimeException ex) {
288                // Ignore failures while cleaning up.
289            }
290        }
291        if (bitmap == null) return null;
292
293        // Scale down the bitmap if it is bigger than we need.
294        int width = bitmap.getWidth();
295        int height = bitmap.getHeight();
296        if (width > targetWidth) {
297            float scale = (float) targetWidth / width;
298            int w = Math.round(scale * width);
299            int h = Math.round(scale * height);
300            bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
301        }
302        return bitmap;
303    }
304
305    public static Thumbnail createThumbnail(Uri uri, Bitmap bitmap, int orientation) {
306        if (bitmap == null) {
307            Log.e(TAG, "Failed to create thumbnail from null bitmap");
308            return null;
309        }
310        return new Thumbnail(uri, bitmap, orientation);
311    }
312}
313