- 本人转载使用
- 方法二尝试后还是有些,方法一没有尝试过。
方法一:
- protected Bitmap safeDecodeStream(Uri uri, int width, int height)
- throws FileNotFoundException{
- int scale = 1;
- BitmapFactory.Options options = new BitmapFactory.Options();
- android.content.ContentResolver resolver = this.ctx.getContentResolver();
- if(width>0 || height>0){
- // Decode image size without loading all data into memory
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeStream(
- new BufferedInputStream(resolver.openInputStream(uri), 16*1024),
- null,
- options);
- int w = options.outWidth;
- int h = options.outHeight;
- while (true) {
- if ((width>0 && w/2 < width)
- || (height>0 && h/2 < height)){
- break;
- }
- w /= 2;
- h /= 2;
- scale *= 2;
- }
- }
- // Decode with inSampleSize option
- options.inJustDecodeBounds = false;
- options.inSampleSize = scale;
- return BitmapFactory.decodeStream(
- new BufferedInputStream(resolver.openInputStream(uri), 16*1024),
- null,
- options);
- }
方法二:
- /**
- * 加载大图片工具类:解决android加载大图片时报OOM异常
- * 解决原理:先设置缩放选项,再读取缩放的图片数据到内存,规避了内存引起的OOM
- * @author: 张进
- * @time:2011/7/28
- */
- public class BitmapUtil {
- public static final int UNCONSTRAINED = -1;
- /*
- * 获得设置信息
- */
- public static Options getOptions(String path){
- Options options = new Options();
- options.inJustDecodeBounds = true;//只描边,不读取数据
- BitmapFactory.decodeFile(path, options);
- return options;
- }
- /**
- * 获得图像
- * @param path
- * @param options
- * @return
- * @throws FileNotFoundException
- */
- public static Bitmap getBitmapByPath(String path, Options options , int screenWidth , int screenHeight)throws FileNotFoundException{
- File file = new File(path);
- if(!file.exists()){
- throw new FileNotFoundException();
- }
- FileInputStream in = null;
- in = new FileInputStream(file);
- if(options != null){
- Rect r = getScreenRegion(screenWidth,screenHeight);
- int w = r.width();
- int h = r.height();
- int maxSize = w > h ? w : h;
- int inSimpleSize = computeSampleSize(options, maxSize, w * h);
- options.inSampleSize = inSimpleSize; //设置缩放比例
- options.inJustDecodeBounds = false;
- }
- Bitmap b = BitmapFactory.decodeStream(in, null, options);
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return b;
- }
- private static Rect getScreenRegion(int width , int height) {
- return new Rect(0,0,width,height);
- }
- /**
- * 获取需要进行缩放的比例,即options.inSampleSize
- * @param options
- * @param minSideLength
- * @param maxNumOfPixels
- * @return
- */
- public static int computeSampleSize(BitmapFactory.Options options,
- int minSideLength, int maxNumOfPixels) {
- int initialSize = computeInitialSampleSize(options, minSideLength,
- maxNumOfPixels);
- int roundedSize;
- if (initialSize <= 8) {
- roundedSize = 1;
- while (roundedSize < initialSize) {
- roundedSize <<= 1;
- }
- } else {
- roundedSize = (initialSize + 7) / 8 * 8;
- }
- return roundedSize;
- }
- private static int computeInitialSampleSize(BitmapFactory.Options options,
- int minSideLength, int maxNumOfPixels) {
- double w = options.outWidth;
- double h = options.outHeight;
- int lowerBound = (maxNumOfPixels == UNCONSTRAINED) ? 1 :
- (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
- int upperBound = (minSideLength == UNCONSTRAINED) ? 128 :
- (int) Math.min(Math.floor(w / minSideLength),
- Math.floor(h / minSideLength));
- if (upperBound < lowerBound) {
- // return the larger one when there is no overlapping zone.
- return lowerBound;
- }
- if ((maxNumOfPixels == UNCONSTRAINED) &&
- (minSideLength == UNCONSTRAINED)) {
- return 1;
- } else if (minSideLength == UNCONSTRAINED) {
- return lowerBound;
- } else {
- return upperBound;
- }
- }
- }
但是上面的方法也不是万能的,同样在很多的大图片的情况下照样存在,经查看Gallery中的图片加载时候发现同样会有问题,但是这个内存泄漏是在某张图片触发时产生,经过一段时间就没有了,所以GALLERY采用了延迟重新加载的方式再次读取这张图片。所以我们可以借鉴他的这个特点加上我们自己的对图片大小采样率的判断即可以避免这个问题。
protected Bitmap load(RenderView view) {
final Config config = mConfig;
final MediaItem item = mItem;
// Special case for non-MediaStore content URIs, do not cache the
// thumbnail.
String uriString = item.mContentUri;
if (uriString != null) {
Uri uri = Uri.parse(uriString);
if (uri.getScheme().equals("content") && !uri.getAuthority().equals("media")) {
try {
return UriTexture.createFromUri(mContext, item.mThumbnailUri, 128, 128, 0, null);
} catch (IOException e) {
return null;
} catch (URISyntaxException e) {
return null;
}
}
}
// Look up the thumbnail in the disk cache.
if (config == null) {
Bitmap retVal = null;
try {
if (mItem.getMediaType() == MediaItem.MEDIA_TYPE_IMAGE) {
Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
try {
// We first dirty the cache if the timestamp has changed
DiskCache cache = null;
MediaSet parentMediaSet = item.mParentMediaSet;
if (parentMediaSet != null && parentMediaSet.mDataSource != null) {
cache = parentMediaSet.mDataSource.getThumbnailCache();
if (cache == LocalDataSource.sThumbnailCache) {
if (item.mMimeType != null && item.mMimeType.contains("video")) {
cache = LocalDataSource.sThumbnailCacheVideo;
}
final long crc64 = Utils.Crc64Long(item.mFilePath);
if (!cache.isDataAvailable(crc64, item.mDateModifiedInSec * 1000)) {
UriTexture.invalidateCache(crc64, UriTexture.MAX_RESOLUTION);
}
}
}
retVal = UriTexture.createFromUri(mContext, mItem.mContentUri, UriTexture.MAX_RESOLUTION,
UriTexture.MAX_RESOLUTION, Utils.Crc64Long(item.mFilePath), null);
} catch (IOException e) {
;
} catch (URISyntaxException e) {
;
}
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
} else {
Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
new Thread() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
;
}
try {
MediaStore.Video.Thumbnails.cancelThumbnailRequest(mContext.getContentResolver(), mItem.mId);
} catch (Exception e) {
;
}
}
}.start();
retVal = MediaStore.Video.Thumbnails.getThumbnail(mContext.getContentResolver(), mItem.mId,
MediaStore.Video.Thumbnails.MINI_KIND, null);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
} catch (OutOfMemoryError e) {
Log.i(TAG, "Bitmap creation fail, outofmemory");
view.handleLowMemory();
try {
if (!mIsRetrying) {
Thread.sleep(1000);
mIsRetrying = true;
retVal = load(view);
}
} catch (InterruptedException eInterrupted) {
}
}
return retVal;
} else {
byte[] data = null;
MediaSet parentMediaSet = item.mParentMediaSet;
if (parentMediaSet != null && !parentMediaSet.mIsLocal) {
DiskCache thumbnailCache = parentMediaSet.mDataSource.getThumbnailCache();
data = thumbnailCache.get(item.mId, 0);
if (data == null) {
// We need to generate the cache.
try {
Bitmap retVal = UriTexture.createFromUri(mContext, item.mThumbnailUri, 256, 256, 0, null);
data = CacheService.writeBitmapToCache(thumbnailCache, item.mId, item.mId, retVal, config.thumbnailWidth,
config.thumbnailHeight, item.mDateModifiedInSec * 1000);
} catch (IOException e) {
return null;
} catch (URISyntaxException e) {
return null;
}
}
} else {
long dateToUse = (item.mDateAddedInSec > item.mDateModifiedInSec) ? item.mDateAddedInSec : item.mDateModifiedInSec;
data = CacheService.queryThumbnail(mContext, Utils.Crc64Long(item.mFilePath), item.mId,
item.getMediaType() == MediaItem.MEDIA_TYPE_VIDEO, dateToUse * 1000);
}
if (data != null) {
try {
// Parse record header.
final ByteArrayInputStream cacheInput = new ByteArrayInputStream(data);
final DataInputStream dataInput = new DataInputStream(cacheInput);
item.mThumbnailId = dataInput.readLong();
item.mThumbnailFocusX = dataInput.readShort();
item.mThumbnailFocusY = dataInput.readShort();
// Decode the thumbnail.
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = true;
options.inScaled = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
final Bitmap bitmap = BitmapFactory.decodeByteArray(data, CACHE_HEADER_SIZE, data.length - CACHE_HEADER_SIZE,
options);
return bitmap;
} catch (IOException e) {
// Fall through to regenerate the cached thumbnail.
}
}
}
return null;
}