Convert Data-URL to BufferedImage

爱⌒轻易说出口 提交于 2019-11-30 06:49:16

As the comments already said the image data is Base64 encoded. To retrieve the binary data you have to strip the type/encoding headers, then decode the Base64 content to binary data.

String encodingPrefix = "base64,";
int contentStartIndex = dataUrl.indexOf(encodingPrefix) + encodingPrefix.length();
byte[] imageData = Base64.decodeBase64(dataUrl.substring(contentStartIndex));

I use org.apache.commons.codec.binary.Base64 from apaches common-codec, other Base64 decoders should work as well.

The only one problem with RFC2397 string is its specification with everything before data but data: and , optional:

data:[<mediatype>][;base64],<data>

So pure Java 8 solution accounting this would be:

final int dataStartIndex = dataUrl.indexOf(",") + 1;
final String data = dataUrl.substring(dataStartIndex);
byte[] decoded = java.util.Base64.getDecoder().decode(data);

Of course dataStartIndex should be checked.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!