2

I have many images in a folder. I want to make one byte array for all of the images (array of byte arrays), but I only managed to make an array for one image.

File file = new File("D:\\swim\\swim99.png");
//init array with file length
byte[] bytesArray = new byte[(int) file.length()];

FileInputStream fis = new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();
System.out.print(Arrays.toString(bytesArray));

So can I access multiple of images in a folder at once and get each one's byte array then put them into a 2D array of arrays array where the [Number of image[byte array image one]]?

Output expected : A[image Number][It's byte array]

Saso
  • 74
  • 12
  • Why? Normally you will be displaying images, so you should be creating them directly from an input stream. You don't want another copy of the data in memory. – user207421 Jun 01 '21 at 03:27

1 Answers1

3

Before we fix your problem, your code actually is quite broken in other ways.

[1] You must close a resource, and safely - and this is not safe. use try-with-resources.

[2] .read(byteArr) does not do what you think it does. It reads at least 1 byte (unless I/O error or end of file is reached), but doesn't neccessarily read all of them. It reads as many as can be swiftly provided. For larger files, that will not be all bytes.

The fix is trivial - stop using obsolete, 25 year old APIs.

Path p = Paths.get("/path/to/imagefile");
byte[] data = Files.readAllBytes(p);

solves all problems, and is much simpler.

As for the array question - that's basic java 101. I suggest you follow the tutorial about arrays.

byte[][] allImages = new byte[10][];
Path imgFolder = Paths.get("/folder/to/images");
for (int i = 0; i < 10; i++) {
    allImages[i] = Files.readAllBytes(imgFolder.resolve(i + ".png"));
}

That assumes you have files /folder/to/images/0.png to .../9.png.

If these images are part of your java app that you intend to ship, you don't want any of this, you're looking for getResourceAsStream instead - because java apps are distributed as jar files, and the images should be inside, which would make them not-a-file.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72