android 从资源中获取位图或声音
我需要从资产中获取位图和声音。我尝试这样做:
BitmapFactory.decodeFile("file:///android_asset/Files/Numbers/l1.png");
像这样:
getBitmapFromAsset("Files/Numbers/l1.png");
private Bitmap getBitmapFromAsset(String strName) {
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open(strName);
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(istr);
return bitmap;
}
但我只得到自由空间,而不是图像。
如何做到这一点?
I need to get Bitmap and sound from assets. I try to do like this:
BitmapFactory.decodeFile("file:///android_asset/Files/Numbers/l1.png");
And like this:
getBitmapFromAsset("Files/Numbers/l1.png");
private Bitmap getBitmapFromAsset(String strName) {
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open(strName);
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(istr);
return bitmap;
}
But I get just free space, not image.
How to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
接受的答案永远不会关闭
InputStream
。以下是在资产文件夹中获取位图的实用方法:The accepted answer never closes the
InputStream
. Here is a utility method for getting aBitmap
in the assets folder:Kotlin 方式,自动关闭输入流。您必须自行处理异常。
Kotlin way, with auto close of the input stream. You have to handle exceptions on your own.
获取存储在 Assets 文件夹中的图像位图的方法。
调整位图大小的方法。
Method to get bitmap of image which is stored in Assets folder.
Method to resize the bitmap.
该路径只是您的文件名 fx bitmap.png。如果您使用子文件夹 bitmap/ 则其 bitmap/bitmap.png
the path is simply your file name fx bitmap.png. if you use subfolder bitmap/ then its bitmap/bitmap.png
使用此代码其工作
更新
在解码位图时,如果图像尺寸很大,我们更经常会遇到内存溢出异常。因此,阅读文章如何有效地显示图像会对您有所帮助。
Use this code its working
Update
While decoding Bitmap we more often meet with memory overflow exception if Image size is very big. So reading article How to display Image efficiently will help you.
简短的 Kotlin 版本:
Short Kotlin version: