Java Convert Base64 String to Image File

Tags: Java Base64

In this Java tutorial we learn how to decode an encoded Base64 String into image file in Java programming language.

How to convert Base64 String into Image file in Java

In Java to convert a Base64 String to file, firstly we need to decode the string to byte[] array and then write all bytes to the file system.

String base64String = "<Base64 String>";
byte[] decodedBytes = Base64.getDecoder().decode(base64String);
Files.write(Paths.get("D:\\SimpleSolution\\image.png"), decodedBytes);

The following example Java code we show you how to convert an Base64 encoded String to image file at D:\SimpleSolution\image.png in Java program.

Base64ToFileExample1.java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class Base64ToFileExample1 {
    public static void main(String... args) throws IOException {
        String base64String = "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkAQAAAABYmaj5AAAA7ElEQVR42tXUsZHEIAwFUHk2cHZuQDO0QeaWTAN4twK3REYbzNAAyhww1ombvd1NbBHeMQS8CPERAH+MAn9YBWCBzAEGTcR13W8cZaEpoLdpiuA6tIb86JWhHnH1tq7vyk4l53MR3fu0p2pZzbJ8JXiqYtHP6H53uBAH3mKadpg0HRZhRrCZNBHzxnWIadBUbILRbK/KzkXxRhEHNpumMuLXLPOZ4IVoz4flA5LTlTzkO+CkqeU/Sgy65G59q92QptbXLIEZVhXQsblDlxZIy8iPDsmrIn5mdiWui/QCoKr2pq35CUPRf/nBPvUNct67nP2Y9j8AAAAASUVORK5CYII=";

        // Convert Base64 String to File
        byte[] decodedBytes = Base64.getDecoder().decode(base64String);
        Files.write(Paths.get("D:\\SimpleSolution\\image.png"), decodedBytes);
    }
}

Happy Coding 😊

Java Convert File to Base64 String