如何使用 Image 中的 Data URI 作为 InputStream?

2022-01-21 00:00:00 image canvas base64 facebook java

我已从 html5 画布中检索到 base64 数据 uri.在我的 servlet 中,我想解码数据 uri 并将其用作输入流,如下面的xxx"所示.下面的代码是让我将 html5 画布中的图像发布到我的 facebook 帐户中.我正在使用restfb.

I have retrieved the base64 data uri from a html5 canvas. Within my servlet, I would like to decode the data uri and use it as an input stream as shown in "xxx" below. The following coding is for me to post the image in the html5 canvas into my facebook account. I am using restfb.

FacebookType publishPhotoResponse = facebookClient.publish("me/photos", FacebookType.class,
BinaryAttachment.with("test.jpeg", getClass().getResourceAsStream("xxx")),
Parameter.with("message", "Test"));

我怎样才能做到这一点?谢谢.

How can I achieve that? Thanks.

已更新越来越近但仍然无法正常工作!

Updated Getting closer but still not working!

在我的jsp中:

var d = document.getElementById('img').src;
window.location.href = "upload?src=" + d;

在我的 servlet 中:

In my servlet:

String d = req.getParameter("src");
String head = "data:image/jpeg;base64,";
String base64 = d.substring(head.length()-1);

byte[] buf = DatatypeConverter.parseBase64Binary(base64);
ByteArrayInputStream is = new ByteArrayInputStream(buf);

FacebookType publishPhotoResponse = facebookClient.publish("me/photos", FacebookType.class,
BinaryAttachment.with("test.jpeg", is),
Parameter.with("message", "Test"));

我的编码中是否有任何错误,因为它似乎在 servlet 中的某个地方遇到了错误.我无法查看错误,因为它在服务器上运行.

Is there any errors in my coding as it seems to hit error somewhere within the servlet. I can't view the errors as it is running on a server.

推荐答案

这需要与this answer几乎完全相反!或者至少,它的反面.它将 Image 回答为 base 64 String,而这个用例是 StringImage.

This needs almost the exact opposite to this answer! Or at least, the reverse of it. It answers Image to base 64 String, whereas this use-case is String to Image.

查看 javax.xml.bind.DatatypeConverter.parseBase64Binary(String) 得到Stringbyte[]>.

Look to javax.xml.bind.DatatypeConverter.parseBase64Binary(String) to get a byte[] of the String.

使用 byte[] 构造一个 ByteArrayInputStream.

Use the byte[] to construct a ByteArrayInputStream.

相关文章