Write an image from project resources to the byte array

Viewed 1607

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?

1 Answers

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

Related