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?

2
  • new javax.swing.ImageIcon(getClass().getResource("/icons/default_image.png")), alternatively the Method getResourceAsStream Then use stackoverflow.com/questions/1264709/… . What is your overall goal, why do you want to have bytes? How do you want to use the image? Commented Nov 7, 2018 at 7:11
  • I encode an image using Base64 and write it as a string to a file String imageAsString = Base64.getEncoder().encodeToString(array); Commented Nov 7, 2018 at 7:16

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

3 Comments

It's not necessary to use an external library anymore (assuming java 9+ is used): try (InputStream is = getClass.getResourceAsStream()) { byte[] bytes = is.readAllBytes(); ... } ( docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/… )
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.
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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.