I'm trying to display multiple images from a directory using ImageIO
and ByteArrayOutputStream
.
For one image I can do this easily:
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;
}
What is the best approach to display multiple images?
I'm doing the following:
- Create a new Buffered Image with size appropriate to fit the images.
- Get the graphics object from the new Buffered Image
- Draw the images via the graphics object
Here is the code I'm using:
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;
}
Is there a better way to do this? Thank you.