Android加载图片的几种方式
一,获得res/raw目录下的原始图片文件
InputStream is = getResources().openRawResource(R.id.fileNameID) ;
Bitmap bmp=BitmapFactory.decodeStream(is);
虽然raw目录下的图片文件不加载到内存中,但是他也会生成R类中的ID所以方便使用.
bitmap = BitmapFactory.decodeStream(getAssets().open("example.jpg"));
getAssets().open()返回assets文件对应的文件流.
BitmapDrawable bmp=new BitmapDrawable(getAssets().open("andorra.jpg"));
bitmap=bmp.getBitmap()
三,获得sd卡中的图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | File file = new File(Environment.getExternalStorageDirectory(), name); if (!file.exists()) return ; BitmapFactory.Options opts = new BitmapFactory.Options(); //设置为true,代表加载器不加载图片,而是把图片的宽高读出来 opts.inJustDecodeBounds= true ; BitmapFactory.decodeFile(file.getAbsolutePath(), opts); int imageWidth = opts.outWidth; int imageHeight = opts.outHeight; //得到屏幕的宽高 Display display=getWindowManager().getDefaultDisplay(); DisplayMetrics displayMetrics= new DisplayMetrics(); display.getMetrics(displayMetrics); //获得像素大小 int screenWidth=displayMetrics.widthPixels; int screenHeight=displayMetrics.heightPixels; int widthScale=imageWidth/screenWidth; int heightScale=imageHeight/screenHeight; int scale = widthScale > heightScale ? widthScale : heightScale; opts.inJustDecodeBounds= false ; opts.inSampleSize=scale; Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath(), opts); |
其实核心代码就是BitmapFac.decodeFile(file.getAbsolutePath(),opts);这里面的其他代码是防治oom
四,从资源ID直接获取
BitmapFactory.decodeResource(res, resId);//这里面的res就是activity的getResources(),resid就是图片id
五,通过文件
BitmapFactory.decodeFile(pathName);
1 2 3 4 5 6 7 8 | private Bitmap BytesToBitmap( byte [] b) { if (b.length != 0 ) { return BitmapFactory.decodeByteArray(b, 0 , b.length); } else { return null ; } } |
参考资料和推荐阅读:
[1].https://blog.csdn.net/izzxacbbt/article/details/83628821
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】