关于android 图片加载优化
android应用对图片处理算是比较频繁的了,尤其是在程序加载大量图片和高分辨率图片时,最容易产生oom异常,下面是个人平时一些省内存加载方法
方法一:
- public Bitmap decodeFile(String filePath) {
- Bitmap bitmap = null;
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inPurgeable = true;
- try {
- BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(
- options, true);
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- }
- if (mFilePath != null) {
- bitmap = BitmapFactory.decodeFile(mFilePath, options);
- }
- return bitmap;
- }
方法二:
- public Bitmap ReadBitMap(Context context, int resId){
- BitmapFactory.Options opt = new BitmapFactory.Options();
- opt.inPreferredConfig = Bitmap.Config.RGB_565;
- opt.inPurgeable = true;
- opt.inInputShareable = true;
- //获取资源图片
- InputStream is = context.getResources().openRawResource(resId);
- return BitmapFactory.decodeStream(is,null,opt);
- }
如果你的控件大小小于原始图片大小,那么就需要对图片进行压缩处理,来减少内存使用。
现在知道了原图片的尺寸,根据实际情况决定你要加载它缩小多少倍后的图片。例如你用一个128x96的ImageView显示一张1024x768的原图,根本没有必要把原图读加载到内存。
加载一张缩小后的图片到内存,只需要把BitmapFactory.Options对象的inSampleSize设为true,
然后给inSampleSize设一个值就行了(可以理解inSampleSize为n,图片就缩小到1/n大小)。
- public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
- int reqWidth, int reqHeight) {
- // First decode with inJustDecodeBounds=true to check dimensions
- final BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeResource(res, resId, options);
- // Calculate inSampleSize
- options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
- // Decode bitmap with inSampleSize set
- options.inJustDecodeBounds = false;
- return BitmapFactory.decodeResource(res, resId, options);
- }
- public static int calculateInSampleSize(
- BitmapFactory.Options options, int reqWidth, int reqHeight) {
- // Raw height and width of image
- final int height = options.outHeight;
- final int width = options.outWidth;
- int inSampleSize = 1;
- if (height > reqHeight || width > reqWidth) {
- if (width > height) {
- inSampleSize = Math.round((float)height / (float)reqHeight);
- } else {
- inSampleSize = Math.round((float)width / (float)reqWidth);
- }
- }
- return inSampleSize;
- }
方法三:使用内存缓存
对于缓存,没有大小或者规则适用于所有应用,它依赖于你分析自己应用的内存使用确定自己的方案。 缓存太小可能只会增加额外的内存使用,缓存太大可能会导致内存溢出或者应用其它模块可使用内存太小
- private LruCache<String, Bitmap> mMemoryCache;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- ...
- // Get max available VM memory, exceeding this amount will throw an
- // OutOfMemory exception. Stored in kilobytes as LruCache takes an
- // int in its constructor.
- final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
- // Use 1/8th of the available memory for this memory cache.
- final int cacheSize = maxMemory / 8;
- mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
- @Override
- protected int sizeOf(String key, Bitmap bitmap) {
- // The cache size will be measured in kilobytes rather than
- // number of items.
- return bitmap.getByteCount() / 1024;
- }
- };
- ...
- }
- public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
- if (getBitmapFromMemCache(key) == null) {
- mMemoryCache.put(key, bitmap);
- }
- }
- public Bitmap getBitmapFromMemCache(String key) {
- return mMemoryCache.get(key);
- }
加载压缩后的图片到ImageView显示
- public void loadBitmap(int resId, ImageView imageView) {
- final String imageKey = String.valueOf(resId);
- final Bitmap bitmap = getBitmapFromMemCache(imageKey);
- if (bitmap != null) {
- mImageView.setImageBitmap(bitmap);
- } else {
- mImageView.setImageResource(R.drawable.image_placeholder);
- BitmapWorkerTask task = new BitmapWorkerTask(mImageView);
- task.execute(resId);
- }
- }
BitmapWorkerTask加载图片后,也要把图片缓存到内存中:
- class BitmapWorkerTask extends AsyncTask {
- ...
- // Decode image in background.
- @Override
- protected Bitmap doInBackground(Integer... params) {
- final Bitmap bitmap = decodeSampledBitmapFromResource(
- getResources(), params[0], 100, 100));
- addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
- return bitmap;
- }
- ...
- }
方法四:使用磁盘缓存
你的应用也有可能被其他任务打断,如电话呼入,应用在后台有可能会被结束,这样缓存的数据也会丢失。 当用户回到应用时,所有的图片还需要重新获取一遍。 磁盘缓存可应用到这种场景中,它可以减少你获取图片的次数,当然,从磁盘获取图片比从内存中获取要慢的多,所以它需要在非UI线程中完成。 示例代码中是磁盘缓存的一个实现,在Android4.0源码中(libcore/luni/src/main/java/libcore/io/DiskLruCache.java), 有更加强大和推荐的一个实现,它的向后兼容使在已发布过的库中很方便使用它
- private DiskLruCache mDiskCache;
- private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
- private static final String DISK_CACHE_SUBDIR = "thumbnails";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- ...
- // Initialize memory cache
- ...
- File cacheDir = getCacheDir(this, DISK_CACHE_SUBDIR);
- mDiskCache = DiskLruCache.openCache(this, cacheDir, DISK_CACHE_SIZE);
- ...
- }
- class BitmapWorkerTask extends AsyncTask {
- ...
- // Decode image in background.
- @Override
- protected Bitmap doInBackground(Integer... params) {
- final String imageKey = String.valueOf(params[0]);
- // Check disk cache in background thread
- Bitmap bitmap = getBitmapFromDiskCache(imageKey);
- if (bitmap == null) { // Not found in disk cache
- // Process as normal
- final Bitmap bitmap = decodeSampledBitmapFromResource(
- getResources(), params[0], 100, 100));
- }
- // Add final bitmap to caches
- addBitmapToCache(String.valueOf(imageKey, bitmap);
- return bitmap;
- }
- ...
- }
- public void addBitmapToCache(String key, Bitmap bitmap) {
- // Add to memory cache as before
- if (getBitmapFromMemCache(key) == null) {
- mMemoryCache.put(key, bitmap);
- }
- // Also add to disk cache
- if (!mDiskCache.containsKey(key)) {
- mDiskCache.put(key, bitmap);
- }
- }
- public Bitmap getBitmapFromDiskCache(String key) {
- return mDiskCache.get(key);
- }
- // Creates a unique subdirectory of the designated app cache directory. Tries to use external
- // but if not mounted, falls back on internal storage.
- public static File getCacheDir(Context context, String uniqueName) {
- // Check if media is mounted or storage is built-in, if so, try and use external cache dir
- // otherwise use internal cache dir
- final String cachePath = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
- || !Environment.isExternalStorageRemovable() ?
- context.getExternalCacheDir().getPath() : context.getCacheDir().getPath();
- return new File(cachePath + File.separator + uniqueName);
- }
运行时的配置改变,例如屏幕横竖屏切换了有好的用户体验,你可能不想在这种情况下,重新获取一遍图片。
幸好你可以使用上面讲的内存缓存。缓存可以通过使用一个Fragment(调用setRetainInstance(true)被传到新的Activity,
当新的Activity被创建后,只需要重新附加Fragment,你就可以得到这个Fragment并访问到存在的缓存,把里面的图片快速的显示出来
- private LruCache mMemoryCache;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- ...
- RetainFragment mRetainFragment =
- RetainFragment.findOrCreateRetainFragment(getFragmentManager());
- mMemoryCache = RetainFragment.mRetainedCache;
- if (mMemoryCache == null) {
- mMemoryCache = new LruCache(cacheSize) {
- ... // Initialize cache here as usual
- }
- mRetainFragment.mRetainedCache = mMemoryCache;
- }
- ...
- }
- class RetainFragment extends Fragment {
- private static final String TAG = "RetainFragment";
- public LruCache mRetainedCache;
- public RetainFragment() {}
- public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
- RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
- if (fragment == null) {
- fragment = new RetainFragment();
- }
- return fragment;
- }
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setRetainInstance(true);
- }
- }
关于android 图片加载优化的更多相关文章
- android 图片加载优化,避免oom问题产生
1,及时回收bitmap,在activity的onstop()和onDestory()里面调用如下代码进行bitmap的回收: // 先判断是否已经回收 if(bitmap != null & ...
- Android图片加载库的理解
前言 这是“基础自测”系列的第三篇文章,以Android开发需要熟悉的20个技术点为切入点,本篇重点讲讲Android中的ImageLoader这个库的一些理解,在Android上最让人头疼是 ...
- 一起写一个Android图片加载框架
本文会从内部原理到具体实现来详细介绍如何开发一个简洁而实用的Android图片加载缓存框架,并在内存占用与加载图片所需时间这两个方面与主流图片加载框架之一Universal Image Loader做 ...
- fackbook的Fresco (FaceBook推出的Android图片加载库-Fresco)
[Android开发经验]FaceBook推出的Android图片加载库-Fresco 欢迎关注ndroid-tech-frontier开源项目,定期翻译国外Android优质的技术.开源库.软件 ...
- Android 图片加载库Glide 实战(二),占位符,缓存,转换自签名高级实战
http://blog.csdn.net/sk719887916/article/details/40073747 请尊重原创 : skay <Android 图片加载库Glide 实战(一), ...
- Android图片加载框架最全解析(八),带你全面了解Glide 4的用法
本篇将是我们这个Glide系列的最后一篇文章. 其实在写这个系列第一篇文章的时候,Glide就推出4.0.0的RC版了.那个时候因为我一直研究的都是Glide 3.7.0版本,再加上RC版本还不太稳定 ...
- Android图片加载框架最全解析(七),实现带进度的Glide图片加载功能
我们的Glide系列文章终于要进入收尾篇了.从我开始写这个系列的第一篇文章时,我就知道这会是一个很长的系列,只是没有想到竟然会写这么久. 在前面的六篇文章中,我们对Glide的方方面面都进行了学习,包 ...
- Android图片加载框架最全解析(一),Glide的基本用法
现在Android上的图片加载框架非常成熟,从最早的老牌图片加载框架UniversalImageLoader,到后来Google推出的Volley,再到后来的新兴军Glide和Picasso,当然还有 ...
- FaceBook推出的Android图片加载库-Fresco
FaceBook推出的Android图片加载库-Fresco 原文链接:Introducing Fresco: A new image library for Android 译者 : ZhaoKai ...
随机推荐
- MyEclipse中Save could not be completed
在MyEclipse下编程时,保存的时候,假设出现例如以下图所看到的错误: - 刘立 - 707903908的博客" src="http://img0.ph.126.net/9y4 ...
- 谷歌高管无意中透露Google Glass未获得成功的原因
Google X高管Astro Teller在接受媒体采访时无意中透露了这款设备没有取得预期成绩的原因 最终我们发现,在他们生活的世界里,数字生活和即时物理生活根本无法融为一体. Teller提出的这 ...
- PHP-Manual的学习----【语言参考】----【类型】-----【Boolean类型】
2017年7月20日15:41:26Boolean 布尔类型 1.这是最简单的类型.boolean 表达了真值,可以为 TRUE 或 FALSE. 其实就是真假的问题.2.语法 要指定一个布尔值,使用 ...
- commons-dbutils:1.6 ——java.sql.SQLException: 不支持的特性
描述:使用jdbc创建连接后,使用commons-dbutils-1.6 数据库工具类,查询报错如下:java.sql.SQLException: 不支持的特性 Query: 经过测试跟踪在commo ...
- jquery获取页面iframe内容
//取得整个HTML格式 var f = $(window.frames["ReportIFrame"].document).contents().html(); 或者 $(&qu ...
- Gaby Ivanushka(快排)
Gaby Ivanushka Once upon a time there lived a tsar that has a daughter — Beautiful Vasilisa. There w ...
- maven3 org.codehaus.plexus.classworlds.launcher.launcher 找不到或无法加载主类
maven3 org.codehaus.plexus.classworlds.launcher.launcher 找不到或无法加载主类 嗯,网上很多资料说是路径的问题,确实是有可能是路径的问题,而且还 ...
- Lattice绘图
lattice包提供了用于可视化单变量和多变量数据的一整套图形系统.许多用户转向使用lattice包是因为它能很容易地生成网格图形.网格图形能够展示变量的分布或变量之间的关系. 例:data(mtca ...
- Android:日常学习笔记(10)———使用LitePal操作数据库
Android:日常学习笔记(10)———使用LitePal操作数据库 引入LitePal 什么是LitePal LitePal是一款开源的Android数据库框架,采用了对象关系映射(ORM)的模式 ...
- Thread.currentThread().getContextClassLoader() and Class.getClassLoader()
Thread.currentThread().getContextClassLoader() and Class.getClassLoader() 一.同一工程中: String path = T ...