2

In the project resource files, I have a default image default_image.png. I need to go to him and translate it into an array of bytes.

Image image = new Image("/icons/default_image.png");
URL defaultImageFile = this.getClass().getResource("/icons/default_image.png");
byte[] array = Files.readAllBytes(Paths.get(defaultImageFile.getPath()));

I can take it to the URL as an image, but I can not as a file. How can I refer to this file as an image by URL?

A1ex NS
  • 57
  • 9
  • `new javax.swing.ImageIcon(getClass().getResource("/icons/default_image.png"))`, alternatively the Method `getResourceAsStream` Then use https://stackoverflow.com/questions/1264709/convert-inputstream-to-byte-array-in-java . What is your overall goal, why do you want to have bytes? How do you want to use the image? – michaeak Nov 07 '18 at 07:11
  • I encode an image using Base64 and write it as a string to a file `String imageAsString = Base64.getEncoder().encodeToString(array);` – A1ex NS Nov 07 '18 at 07:16

1 Answers1

4

I suggest do the following:

Use commons IO, then:

InputStream is = getClass().getResourceAsStream("/icons/default_image.png")
byte[] bytes = IOUtils.toByteArray(is);

(try and catch the exceptions.)

Edit As of Java 9 no Library needed:

InputStream is = getClass().getResourceAsStream("/icons/default_image.png")
byte[] bytes = is.readAllBytes();

(Again try and catch the exceptions.)

michaeak
  • 1,548
  • 1
  • 12
  • 23
  • 1
    It's not necessary to use an external library anymore (assuming java 9+ is used): `try (InputStream is = getClass.getResourceAsStream()) { byte[] bytes = is.readAllBytes(); ... }` ( https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/InputStream.html#readAllBytes() ) – fabian Nov 07 '18 at 08:55
  • Thansk for the hint, in Java 8 it is still necessary to read the bytes, what you show is Java 11. I don't know what the poster of the question uses. – michaeak Nov 07 '18 at 08:58
  • 1
    Just to clarify: The method `readAllBytes` was added in _Java 9_ but the documentation fabian links is for Java 11 (current LTS release as of this comment). – Slaw Nov 07 '18 at 20:56