Recently I needed for my mapjfx project to convert an image, where I had the URL of, to a base64 encoded data-URI. The following code shows how to do the conversion (Java 8 code):
/* * (c) 2015 P.J. Meisch (pj.meisch@sothawo.com). */ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.*; import java.util.Base64; import java.util.logging.Level; import java.util.logging.Logger; public class Test { private static Logger logger = Logger.getAnonymousLogger(); public static URI getDataURIForURL(URL url) { URI dataUri = null; if (null != url) { try (InputStream inStreamGuess = url.openStream(); InputStream inStreamConvert = url.openStream(); ByteArrayOutputStream os = new ByteArrayOutputStream()) { String contentType = URLConnection.guessContentTypeFromStream(inStreamGuess); if (null != contentType) { byte[] chunk = new byte[4096]; int bytesRead; while ((bytesRead = inStreamConvert.read(chunk)) > 0) { os.write(chunk, 0, bytesRead); } os.flush(); dataUri = new URI("data:" + contentType + ";base64," + Base64.getEncoder().encodeToString(os.toByteArray())); } else { logger.warning(() -> "could not get content type from " + url.toExternalForm()); } } catch (IOException e) { logger.log(Level.SEVERE, "error loading data from url", e); } catch (URISyntaxException e) { logger.log(Level.SEVERE, "error building uri", e); } } return dataUri; } public static void main(String[] args) { try { URL url = new File("test.png").toURI().toURL(); logger.info(() -> "url: " + url.toExternalForm()); URI dataURI = getDataURIForURL(url); logger.info(() -> "dataUrl: " + dataURI.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } } }
The logging output is as follows (last line shortened):
Jan 05, 2015 5:22:23 PM Test main INFORMATION: url: file:/Users/sothawo/Test/test.png Jan 05, 2015 5:22:23 PM Test main INFORMATION: dataUrl: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAAAXNSR0IArs4c6QA...
x
contentType getting null
I got a similar error, It seems to only happen when I use a website URL, versus a local file URL always works out.