0

I would add an image to an excel file created using the library jxl:

http://jexcelapi.sourceforge.net/

I try adding 2 images with this code:

 InputStream stream = ClassLoader.getSystemResourceAsStream("images/logo1.png");
byte abyte0[] = new byte[stream.available()];
stream.read(abyte0);
wsheet.addImage(new WritableImage(1, 1, 8, 6, abyte0));






InputStream stream2 = ClassLoader.getSystemResourceAsStream("images/logo2.png");
    byte abyte2[] = new byte[stream2.available()];
    stream2.read(abyte2);
    wsheet.addImage(new WritableImage(1, 11, 5, 34, abyte2));

But the result is not correct. The first image is correctly added, but the second one no.

This is a screenshot of that: enter image description here

The image printed is all black! How can i fix this?

Thank you.

user2520969
  • 1,389
  • 6
  • 20
  • 30

1 Answers1

1

You actually have 2 problems.

First, InputStream.available() gives an estimate of the number of bytes that can be read in the call to read(), not the full size of the stream.

Second, read(byte[]) isn't guaranteed to read the number of bytes returned by available(). Rather, it returns the number of bytes read, or -1 when the end of the stream is reached.

For the proper way to do this, see Convert InputStream to byte array in Java

Community
  • 1
  • 1
GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67