在Android上工作一年后,我在传统Java GUI中有点生气。
我需要知道我打开图像的方式有两件事
但首先是一些代码
/**
* Load the image for the specified frame of animation. Since
* this runs as an applet, we use getResourceAsStream for
* efficiency and so it'll work in older versions of Java Plug-in.
*/
protected ImageIcon loadImage(String imageNum, String extension) {
String path = dir + "/" + imageNum+"."+extension;
int MAX_IMAGE_SIZE = 2400000; //Change this to the size of
//your biggest image, in bytes.
int count = 0;
BufferedInputStream imgStream = new BufferedInputStream(
this.getClass().getResourceAsStream(path));
if (imgStream != null) {
byte buf[] = new byte[MAX_IMAGE_SIZE];
try {
count = imgStream.read(buf);
imgStream.close();
} catch (java.io.IOException ioe) {
System.err.println("Couldn't read stream from file: " + path);
return null;
}
if (count <= 0) {
System.err.println("Empty file: " + path);
return null;
}
return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf));
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
我称之为
loadImage("share_back_img_1_512", "jpg");
我的问题是:如何让它更具活力。
目前我正在测试一些图像,但我有最终小程序的100张图像。
我必须将图像存储在一个包中才能访问它们。
所以这就是问题:
有没有办法根据包的内容加载图像? 获取名称,大小,扩展名......?
基本上是一种生成ImageIcons的简单方法
答案 0 :(得分:1)
您编写流读取的方式 - 它可能导致部分读取,因为只有一次读取调用不能保证返回流最终可能产生的所有字节。
尝试Apache commons IOUtils#toByteArray(InputStream),或者包含您自己的简单实用方法:
public static final byte[] readBytes(final InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(Short.MAX_VALUE);
byte[] b = new byte[Short.MAX_VALUE];
int len = 0;
while ((len = is.read(b)) != -1) {
baos.write(b, 0, len);
}
return baos.toByteArray();
}
至于您的组织问题......没有简单+可靠的方法来获取包内容的“目录列表”。可以跨多个类路径条目定义包,跨越JAR和文件夹甚至网络资源。
如果有问题的软件包包含在一个JAR中,您可以考虑考虑如下所述的内容:http://www.rgagnon.com/javadetails/java-0513.html
更可靠和可移植的方式可能是维护包含要加载的图像列表的文本文件。将列表作为资源加载,然后使用列表循环并加载文本文件中列出的所有图像。