Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Data URI from Image as an InputStream?

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!

In my jsp:

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

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"));

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.

like image 400
Sky Avatar asked Oct 20 '22 23:10

Sky


1 Answers

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.

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

Use the byte[] to construct a ByteArrayInputStream.

like image 176
Andrew Thompson Avatar answered Nov 01 '22 15:11

Andrew Thompson