If the image URL begins with "data", it means that the image data is embedded in the HTML page itself, rather than being stored on a remote server that can be accessed via a URL. Therefore, you cannot download the image using a standard HTTP connection. So, the base64 mechanism helps us.
Image Source URL : data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAWAUNoinFRBWASIUA........AAAAElFTkSuQmCC
To download the image, the below code can be used:
// Get the image source data
String imageData = webElement.getAttribute("src");
// Extract the image data and file extension from the data URL
String[] parts = imageData.split(",");
String mimeType = parts[0].split(":")[1];
String base64Data = parts[1];
String fileExtension = "";
if (mimeType.equals("image/jpeg")) {
fileExtension = ".jpg";
} else if (mimeType.equals("image/png")) {
fileExtension = ".png";
} else if (mimeType.equals("image/gif")) {
fileExtension = ".gif";
} else {
// Unsupported image format
throw new IOException("Unsupported image format");
}
// Set the output file path and stream. Here, we save the image file.
String outputPath = "C:/images/image" + fileExtension;
FileOutputStream outputStream = new FileOutputStream(outputPath);
// Close the output stream
outputStream.close();
This code first extracts the image data from the "data" URL and splits it into its MIME type and base64-encoded data components. It then determines the file extension based on the MIME type and saves the image to a file on disk, after decoding the base64-encoded image data. Note that you will need to handle any exceptions that may occur during the decoding and file I/O processes.
To use this code, you will need to import the following classes in addition to the ones I mentioned in my previous answer:
import java.io.File;
import java.util.Base64;
The java.util.Base64 class is used to decode the base64-encoded image data. The java.io.File class is used to represent the output file on disk.
I hope this might help someone!