您的位置:首页 > 其它

获取Bitmap的几种方式总结

2018-04-03 09:46 513 查看
从获取方式分:(1)以文件流的方式假设在sdcard下有 test.png图片
FileInputStream fis = new FileInputStream("/sdcard/test.png"); Bitmap bitmap=BitmapFactory.decodeStream(fis);
(2)以R文件的方式假设 res/drawable下有 test.jpg文件
Bitmap bitmap =BitmapFactory.decodeResource(getResources(), R.drawable.test);
或BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.test);Bitmap bitmap = bitmapDrawable.getBitmap();
(3)以ResourceStream的方式,不用R文件Bitmap bitmap=BitmapFactory.decodeStream(getClass().getResourceAsStream(“/res/drawable/test.png”));
(4)以文件流+R文件的方式InputStream in = getResources().openRawResource(R.drawable.test);Bitmap bitmap = BitmapFactory.decodeStream(in);或InputStream in = getResources().openRawResource(R.drawable.test);BitmapDrawable bitmapDrawable = new BitmapDrawable(in);Bitmap bitmap = bitmapDrawable.getBitmap();
注意:openRawResource可以打开drawable, sound, 和raw资源,但不能是string和color。
从资源存放路径分:(1)图片放在sdcard中Bitmap imageBitmap = BitmapFactory.decodeFile(path);// (path 是图片的路径,跟目录是/sdcard)

(2)图片在项目的res文件夹下面ApplicationInfo appInfo = getApplicationInfo();//得到该图片的id(name 是该图片的名字,"drawable" 是该图片存放的目录,appInfo.packageName是应用程序的包)int resID = getResources().getIdentifier(fileName, "drawable", appInfo.packageName);Bitmap imageBitmap2 = BitmapFactory.decodeResource(getResources(), resID);
(3)图片放在src目录下String path = "com/xiangmu/test.png"; //图片存放的路径InputStream in = getClassLoader().getResourceAsStream(path); //得到图片流Bitmap imageBitmap3 = BitmapFactory.decodeStream(in);
(4)图片放在Assets目录InputStream in = getResources().getAssets().open(fileName);Bitmap imageBitmap4 = BitmapFactory.decodeStream(in);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: