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 handle cookies using Jakarta Servlet API? - April 19, 2025
- How do I set response headers with HttpServletResponse? - April 18, 2025
- How do I apply gain and balance using FloatControl? - April 18, 2025