Android各种地方图片读取(加载)2014-10-24 16:39:25
( 4人已投票,[高质量] )
Android加载图片是很常见的操作,下面就是如何读取res资源中的图片、读取assets内的图片、读取sd卡内的图片及网络图片的读取
一:读取res中的图片
//读取本地res中的图片 publicstaticBitmap readBitmap(intresid){ BitmapFactory.Options opt = newBitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; //获取资源图片 InputStream input = getResources().openRawResource(resid); returnBitmapFactory.decodeStream(input,null,opt); } //回收资源(很重要) publicstaticvoidrecycle(Bitmap bitmap){ if(bitmap!=null && !bitmap.isRecycle()){ bitmap.recycle(); System.gc();//及时回收 } }
二:放在assets中的图片
InputStream is = context.getResources().getAssets().open("icon.png"); Bitmap bitmap = BitmapFactory.decodeStream(is);
三:读取sd卡中的图片
Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/icon.png");
四:读取网络图片
publicstaticBitmap loadImageFromUrl(String urlStr){ URL url; InputStream i = null; try{ m = newURL(urlStr); i = m.getContent(); }catch(Exception e){ e.printStaceTrace(); } returnBitmapFactory.decodeStream(i); }
以上为自种图片加载方式,喜欢就收藏吧~