Issue
I am experimenting with saving project data (images, parameters etc) in a save file. The way I found is to incorporate all the data in XML file, so I decided to convert image to Base64 string. The obstacle here is that I don't know how to get the image back from string.
File file = new File("image_path");
byte[] bytes = new byte[(int)file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
String ef = Base64.getEncoder().encodeToString(bytes);
Image image = new Image(file.toURI().toString());
when I try to use decoder inside the same function, it always print false.
byte[] ds = Base64.getDecoder().decode(ef);
if(ds==bytes) {
System.out.println("True");
}else {
System.out.println("false");
}
All examples I found on the site are outdated. So what is the right way to convert string back to file without loss of data. Thanks in advance.
Solution
Path path = Paths.get("...");
byte[] bytes = Files.readAllBytes(path);
And then
byte[] img = Base64.getDecoder().decode(bytes);
Or with better memory usage:
InputStream in = Base64.getDecoder().wrap(Files.newInputStream(path));
Image image = new Image(in);
One problem is that there are several Base64 classes historically, you need java.util.Base64
.
Answered By - Joop Eggen
Answer Checked By - Katrina (JavaFixing Volunteer)