如何从资源中加载图像?
我需要从资源中加载图像,以避免在某些特定情况下调整 POT 图像大小时出现 froyo 2.2.2 错误。避免这种情况的方法是从资产目录加载图像文件。
我正在尝试这样做:
String imagePath = "radiocd5.png";
AssetManager mngr = context.getAssets();
// Create an input stream to read from the asset folder
InputStream is = null;
try {
is = mngr.open(imagePath);
} catch (IOException e1) { e1.printStackTrace();}
//Get the texture from the Android resource directory
//InputStream is = context.getResources().openRawResource(R.drawable.radiocd5);
Bitmap bitmap = null;
try {
//BitmapFactory is an Android graphics utility for images
bitmap = BitmapFactory.decodeStream(is);
} finally {
//Always clear and close
try {
is.close();
is = null;
} catch (IOException e) {}
}
但是我在 is.close(); 线上收到 NullPointerException;
我捕获了 FileNotFoundException:radicd5.png,但该文件位于我的资产目录中:S
什么我做得不好吗?该文件名为 radiocd5.png
,位于 assets
目录中
i need to load a image from assets to avoid a froyo 2.2.2 bug resizing POT images in some particular cases. The way to avoid it is loading the image files from assets dir.
I'm trying to do with this:
String imagePath = "radiocd5.png";
AssetManager mngr = context.getAssets();
// Create an input stream to read from the asset folder
InputStream is = null;
try {
is = mngr.open(imagePath);
} catch (IOException e1) { e1.printStackTrace();}
//Get the texture from the Android resource directory
//InputStream is = context.getResources().openRawResource(R.drawable.radiocd5);
Bitmap bitmap = null;
try {
//BitmapFactory is an Android graphics utility for images
bitmap = BitmapFactory.decodeStream(is);
} finally {
//Always clear and close
try {
is.close();
is = null;
} catch (IOException e) {}
}
But i am getting NullPointerException on the line is.close();
i capture a FileNotFoundException: radiocd5.png, but that file is on my assets directory :S
What am i doing bad? The file is called radiocd5.png
and it is on the assets
directory
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以按照我的教程来显示资产中的数据: https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
带有加载图像和要显示的文本的示例。
我现在添加了所提供链接的相关部分
(如果发生地震或其他什么情况);-) Taifun
You can follow my tutorials on displaying data from Assets: https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
The sample with loading image and text to display.
I now added the relevant part of the provided link
(in case of earthquake or something) ;-) Taifun
不要使用资源目录,而是将文件放入 /res/raw,然后您可以使用以下 URI 访问它:
android.resource://com.your.packagename/" + R.raw.radiocd5< /代码>
Instead of using the assets dir, put the file into /res/raw, and you can then access it using the following URI:
android.resource://com.your.packagename/" + R.raw.radiocd5
这是另一种方法
Here is an alternative way
另一个版本,在片段内:
这个过程在 iOS/UIKit 或 iOS/SwiftUI 中似乎要简单得多。
Another version, inside a fragment:
This process seems much simpler in iOS/UIKit or iOS/SwiftUI.