我正在尝试使用ImageIO
和ByteArrayOutputStream
显示目录中的多个图片。
对于一张图片,我可以轻松完成这项工作:
public byte[] getImage() {
try {
InputStream inputStream = new FileInputStream("image.jpg");
BufferedImage bufferedImage = ImageIO.read(inputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
System.out.println(e.getMessage());
}
return null;
}
显示多张图片的最佳方法是什么?
我正在做以下事情:
以下是我正在使用的代码:
public byte[] retrieveFaceDb() {
// TODO:
String faceDbPath = Utils.commandLineArgs[2];
File dir = new File(faceDbPath);
if (dir.isDirectory()) {
ByteArrayOutputStream finalByteArrayOutputStream = new ByteArrayOutputStream();
BufferedImage[] buffImages = new BufferedImage[10];
int type = 0;
int idx = 0;
for (final File f : dir.listFiles()) {
try {
buffImages[idx] = ImageIO.read(f);
type = buffImages[idx].getType();
idx ++;
} catch (final IOException e) {
// handle errors here
}
}
int num = 0;
BufferedImage finalBufferedImage = new BufferedImage(buffImages[0].getWidth()*10, buffImages[0].getHeight(), type);
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 10; j++) {
finalBufferedImage.createGraphics().drawImage(buffImages[num], buffImages[0].getWidth()*j, buffImages[0].getHeight()*i, null);
num ++;
}
}
try {
ImageIO.write(finalBufferedImage, "png", finalByteArrayOutputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return finalByteArrayOutputStream.toByteArray();
// try {
// return java.nio.file.Files.readAllBytes(dir.toPath());
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
return null;
}
有更好的方法吗?谢谢。