1 /* 2 * Copyright (C) 2010 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.gallery3d.data; 18 19 import com.android.gallery3d.app.GalleryApp; 20 import com.android.gallery3d.common.BitmapUtils; 21 import com.android.gallery3d.data.ImageCacheService.ImageData; 22 import com.android.gallery3d.util.ThreadPool.Job; 23 import com.android.gallery3d.util.ThreadPool.JobContext; 24 25 import android.graphics.Bitmap; 26 import android.graphics.BitmapFactory; 27 28 abstract class ImageCacheRequest implements Job<Bitmap> { 29 private static final String TAG = "ImageCacheRequest"; 30 31 protected GalleryApp mApplication; 32 private Path mPath; 33 private int mType; 34 private int mTargetSize; 35 36 public ImageCacheRequest(GalleryApp application, 37 Path path, int type, int targetSize) { 38 mApplication = application; 39 mPath = path; 40 mType = type; 41 mTargetSize = targetSize; 42 } 43 44 public Bitmap run(JobContext jc) { 45 String debugTag = mPath + "," + 46 ((mType == MediaItem.TYPE_THUMBNAIL) ? "THUMB" : 47 (mType == MediaItem.TYPE_MICROTHUMBNAIL) ? "MICROTHUMB" : "?"); 48 ImageCacheService cacheService = mApplication.getImageCacheService(); 49 50 ImageData data = cacheService.getImageData(mPath, mType); 51 if (jc.isCancelled()) return null; 52 53 if (data != null) { 54 BitmapFactory.Options options = new BitmapFactory.Options(); 55 options.inPreferredConfig = Bitmap.Config.ARGB_8888; 56 Bitmap bitmap = DecodeUtils.requestDecode(jc, data.mData, 57 data.mOffset, data.mData.length - data.mOffset, options); 58 if (bitmap == null && !jc.isCancelled()) { 59 Log.w(TAG, "decode cached failed " + debugTag); 60 } 61 return bitmap; 62 } else { 63 Bitmap bitmap = onDecodeOriginal(jc, mType); 64 if (jc.isCancelled()) return null; 65 66 if (bitmap == null) { 67 Log.w(TAG, "decode orig failed " + debugTag); 68 return null; 69 } 70 71 if (mType == MediaItem.TYPE_MICROTHUMBNAIL) { 72 bitmap = BitmapUtils.resizeDownAndCropCenter(bitmap, 73 mTargetSize, true); 74 } else { 75 bitmap = BitmapUtils.resizeDownBySideLength(bitmap, 76 mTargetSize, true); 77 } 78 if (jc.isCancelled()) return null; 79 80 byte[] array = BitmapUtils.compressBitmap(bitmap); 81 if (jc.isCancelled()) return null; 82 83 cacheService.putImageData(mPath, mType, array); 84 return bitmap; 85 } 86 } 87 88 public abstract Bitmap onDecodeOriginal(JobContext jc, int targetSize); 89 } 90