In the previous example, How do I convert an image file to a Base64 string?, you’ve seen how to convert image file to base64 string.
In this example, you will see how you can convert a base64 string back into an image file. Below are examples of how to do this in Java, using the Java 8 native java.util.Base64
class.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class Base64ToImage {
public static void main(String[] args) throws Exception {
// this is your Base64 encoded string
String base64String = "iVBORw0...";
byte[] decodedBytes = Base64.getDecoder().decode(base64String);
Files.write(Paths.get("/path/to/your/outputimage.png"), decodedBytes);
}
}
Just replace “/path/to/your/outputimage.png” with the actual path where you want to save the image.
This code will decode the base64 string back into a byte array, and then it will write this byte array into an image file. Be careful with the format of the image (PNG, JPG, etc.) as the format of the output file should match the format of the original base64-encoded image.
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024