I thought I would find a solution to this problem relatively easily, but here I am calling upon the help from ye gods to pull me out of this conundrum.
So, I've got an image and I want to store it in an XML document using Java. I have previously achieved this in VisualBasic by saving the image to a stream, converting the stream to an array, and then VB's xml class was able to encode the array as a base64 string. But, after a couple of hours of scouring the net for an equivalent solution in Java, I've come back empty handed. The only success I have had has been by:
import it.sauronsoftware.base64.*;
import java.awt.image.BufferedImage;
import org.w3c.dom.*;
...
BufferedImage img;
Element node;
...
java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream();
ImageIO.write(img, "png", os);
byte[] array = Base64.encode(os.toByteArray());
String ss = arrayToString(array, ",");
node.setTextContent(ss);
...
private static String arrayToString(byte[] a, String separator) {
StringBuffer result = new StringBuffer();
if (a.length > 0) {
result.append(a[0]);
for (int i=1; i<a.length; i++) {
result.append(separator);
result.append(a[i]);
}
}
return result.toString();
}
Which is okay I guess, but reversing the process to get it back to an image when I load the XML file has proved impossible. If anyone has a better way to encode/decode an image in an XML file, please step forward, even if it's just a link to another thread that would be fine.
Cheers in advance,
Hoopla.
I've done something similar (encoding and decoding in Base64) and it worked like a charm. Here's what I think you should do, using the class Base64 from the Apache Commons project:
// ENCODING
BufferedImage img = ImageIO.read(new File("image.png"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
baos.flush();
String encodedImage = Base64.encodeToString(baos.toByteArray());
baos.close(); // should be inside a finally block
node.setTextContent(encodedImage); // store it inside node
// DECODING
String encodedImage = node.getTextContent();
byte[] bytes = Base64.decode(encodedImage);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
Hope it helps.
Apache Commons has a Base64 class that should be helpful to you:
From there, you can just write out the bytes (they are already in a readable format)
After you get your byte array
byte[] array = Base64.encode(os.toByteArray());
use an encoded String :
String encodedImg = new String( array, "utf-8");
Then you can do fun things in your xml like
<binImg string-encoding="utf-8" bin-encoding="base64" img-type="png"><![CDATA[ encodedIImg here ]]></binImg>
With Java 6, you can use DatatypeConverter to convert a byte array to a Base64 string:
byte[] imageData = ...
String base64String = DatatypeConverter.printBase64Binary(imageData);
And to convert it back:
String base64String = ...
byte[] imageData = DatatypeConverter.parseBase64Binary(base64String);
Your arrayToString() method is rather bizarre (what's the point of that separator?). Why not simply say
String s = new String(array, "US-ASCII");
The reverse operation is
byte[] array = s.getBytes("US-ASCII");
Use the ASCII encoding, which should be sufficient when dealing with Base64 encoded data. Also, I'd prefer a Base64 encoder from a reputable source like Apache Commons.
You don't need to invent your own XML data type for this. XML schema defines standard binary data types, such as base64Binary, which is exactly what you are trying to do.
Once you use the standard types, it can be converted into binary automatically by some parsers (like XMLBeans). If your parser doesn't handle it, you can find classes for base64Binary in many places since the datatype is widely used in SOAP, XMLSec etc.
most easy implementation I was able to made is as below, And this is from Server to Server XML transfer containing binary data Base64 is from the Apache Codec library:
- Reading binary data from DB and create XML
Blob blobData = oRs.getBlob("ClassByteCode");
byte[] bData = blobData.getBytes(1, (int)blobData.length());
bData = Base64.encodeBase64(bData);
String strClassByteCode = new String(bData,"US-ASCII");
on requesting server read the tag and save it in DB
byte[] bData = strClassByteCode.getBytes("US-ASCII");
bData = Base64.decodeBase64(bData);
oPrStmt.setBytes( ++nParam, bData );
easy as it can be..
I'm still working on implementing the streaming of the XML as it is generated from the first server where the XML is created and stream it to the response object, this is to take care when the XML with binary data is too large.
Vishesh Sahu
The basic problem is that you cannot have an arbitrary bytestream in an XML document, so you need to encode it somehow. A frequent encoding scheme is BASE64, but any will do as long as the recipient knows about it.
I know that the question was aking how to encode an image via XML, but it is also possible to just stream the bytes via an HTTP GET request instead of using XML and encoding an image. Note that input is a FileInputStream.
Server Code:
File f = new File(uri_string);
FileInputStream input = new FileInputStream(f);
OutputStream output = exchange.getResponseBody();
int c = 0;
while ((c = input.read()) != -1) {
output.write(c); //writes each byte to the exchange.getResponseBody();
}
result = new DownloadFileResult(int_list);
if (input != null) {input.close();}
if (output != null){ output.close();}
Client Code:
InputStream input = connection.getInputStream();
List<Integer> l = new ArrayList<>();
int b = 0;
while((b = input.read()) != -1){
l.add(b);//you can do what you wish with this list of ints ie- write them to a file. see code below.
}
Here is how you would write the Integer list to a file:
FileOutputStream out = new FileOutputStream("path/to/file.png");
for(int i : result_bytes_list){
out.write(i);
}
out.close();
node.setTextContent( base64.encodeAsString( fileBytes ) )
using org.apache.commons.codec.binary.Base64
Related
I need to save a pdf document, generated by aspose.pdf for java library to memory (without using temporary file)
I was looking at the documentation and didn't find the save method with the appropriate signature. (I was looking for some kind of outputstream, or at least byte array).
Is it possible? If it is, how can I manage that?
Thanks
Aspose.Pdf for Java supports saving output to both file and stream. Please check following code snippet, It will help you to accomplish the task.
byte[] input = getBytesFromFile(new File("C:/data/HelloWorld.pdf"));
ByteArrayOutputStream output = new ByteArrayOutputStream();
com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document(new ByteArrayInputStream(input));
pdfDocument.save(output);
//If you want to read the result into a Document object again, in Java you need to get the
//data bytes and wrap into an input stream.
InputStream inputStream=new ByteArrayInputStream(output.toByteArray());
I am Tilal Ahmad, developer evangelist at Aspose.
I did similar thing.
Here is method to write data to byte:
public byte[] toBytes() {
//create byte array output stream object
ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
//create new data output stream object
DataOutputStream outStream = new DataOutputStream(byteOutStream);
try {//write data to bytes stream
if (data != null) {
outStream.write(data);//write data
}//return array of bytes
return byteOutStream.toByteArray();
}
Then you do something like
yourFileName.toBytes;
I have a set of serialized images which I want to deserialize. The data looks like the following:
GIF89ax\000\364\001\367\000\000\000\000\000\001\001\001\002\002\002\003\003\003\004\004\004\005\005\005\006\006\006\a\a\a\b\b\b\t\t\t\n\n\n\v\v\v\f\f\f\r\r\ ...
Due to data privacy I cann't post an full image. I have trouble to find out what kind of encoding this is. Now I'm struggeling to find a away to convert this to an BufferedImage in Java.
It turned out that the images were serialzed with Google-Protocoll Buffer TextFormat. So the code which converted the code correctly is
import com.google.protobuf.ByteString;
import com.google.protobuf.TextFormat;
String imgStr = "GIF89ax\000\364\001\367\000\000\000\000\000\001\001\001\002\002\002\003\003\003\004\004\004\005\005\005\006\006\006\a\a\a\b\b\b\t\t\t\n\n\n\v\v\v\f\f\f\r\r\ ..."; // must an full image string
ByteString unescapeBytes = TextFormat.unescapeBytes(imgStr);
byte[] bytes = new byte[unescapeBytes.size()];
unescapeBytes.copyTo(bytes, 0);
final BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream("result.gif"));
bw.write(bytes);
bw.close();
Thats it.
My application get the String representation of bytes. I need to convert it byte[] array. I am using below code but it is not working.
byte[] bytesArray = myString.getBytes();
Can anyone help what is the correct way to convert it to byte[].
EDIT:
hi all, My code is here http://pastebin.com/87jGprtD/. I have one base64 code. This base64 has content for text and imagedata both. I want to download/create an image from this code. When I decode I get the byte[] for both text and imagedata. I convert it string because I have to differentiate the each part. I used spilt with some delimiter now i have an array of string. This string contains the imagedata. I have to convert it back to bytes to create an image. please check code for the same. please
Here is the relevant code:
byte[] imageByteArray = Base64.decodeBase64(imageDataString);
System.out.println(new String(imageByteArray));
String[] contentArray = new String(imageByteArray).split("--1_520B30B0_E358708");
for (int i = 0; i < contentArray.length; i++) {
if (i == 2) {
String[] parts = contentArray[i].split("binary");
InputStream is = new ByteArrayInputStream((parts[1].trim()).getBytes());
ImageInputStream iis = ImageIO.createImageInputStream(is);
System.out.println(iis);
image = ImageIO.read(iis);
ImageIO.write(image, "JPG", new File("E:/test1.JPG"));
}
}
You are decoding Base64 data into byte[], then converting that to String. You can't do that -- "binary" data cannot be converted to String and back to "binary" without data loss.
I have a web service that I am re-writing from VB to a Java servlet. In the web service, I want to extract the body entity set on the client-side as such:
StringEntity stringEntity = new StringEntity(xml, HTTP.UTF_8);
stringEntity.setContentType("application/xml");
httppost.setEntity(stringEntity);
In the VB web service, I get this data by using:
Dim objReader As System.IO.StreamReader
objReader = New System.IO.StreamReader(Request.InputStream)
Dim strXML As String = objReader.ReadToEnd
and this works great. But I am looking for the equivalent in Java.
I have tried this:
ServletInputStream dataStream = req.getInputStream();
byte[] data = new byte[dataStream.toString().length()];
dataStream.read(data);
but all it gets me is an unintelligible string:
data = [B#68514fec
Please advise.
You need to use a ByteArrayOutputStream, like this:
ServletInputStream dataStream = req.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int r;
byte[] buffer = new byte[1024*1024];
while ((r = dataStream.read(data, 0, buffer.length)) != -1) {
baos.write(buffer, 0, r);
}
baos.flush();
byte[] data = baos.toByteArray();
You are confusing with printing of java arrays. When you print any java object it is transformed to its string representation by implicit invocation of toString() method. Array is an object too and its toString() implementation is not too user friendly: it creates string that contains [, then symbolic type definition (B for byte in your case, then the internal reference to the array.
If you want to print the array content use Arrays.toString(yourArray). This static method creates user-friendly string representation of array. This is what you need here.
And yet another note. You do not read your array correctly. Please take a look on #Petter`s answer (+1) - you have to implement a loop to read all bytes from the stream.
This is an example XML file that would come from the Android Client.
<test>
<to>Mee</to>
<from>Youuu</from>
<img src="http://www.domain.com/path/to/my/image.jpg" />
</test>
I have written a XML parser about this. My problem is while passing it to the Android Client, I need to have the image binary data instead of the image path. How can I accomplish this and how can I update the above said XML with the binary data.
You could use Base64 to encode your image binary data (represented by a byte[]) and include it in the xml as CDATA.
Then on the Android machine, you just decode it to a byte array, and render the image.
You can use Apache Commons to encode/decode.
Edit:
You need to get a byte representation of the image data in order to convert it. See my example. This is using sun.misc.BASE64Decoder and sun.misc.BASE64Encoder, you may need to adapt depending on what you have at your disposal on Android (see Apache Commons).
public class SO11096275 {
public static byte[] readImage(URL url) throws IOException {
final ByteArrayOutputStream bais = new ByteArrayOutputStream();
final InputStream is = url.openStream();
try {
int n;
byte[] b = new byte[4096];
while ((n = is.read(b)) > 0) {
bais.write(b, 0, n);
}
return bais.toByteArray();
} finally {
if (is != null) {
is.close();
}
}
}
public static void main(String[] args) throws Exception {
URL url = new URL("http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png");
byte[] imgData = readImage(url);
String imgBase64 = new BASE64Encoder().encode(imgData);
System.out.println(imgBase64);
byte[] decodedData = new BASE64Decoder().decodeBuffer(imgBase64);
FileUtils.writeByteArrayToFile(new File("/path/to/wikipedia-logo.png"), decodedData); // apache commons
}
}
Then you have your image data as a string in imgBase64, you just have to append a node to your xml using the DOM implementation you want, for example dom4j. There are methods to add CDATA to the XML. Finally, on your Android, you just need to retrieve the node content and you're good to decode it like above and do what you want with the image.
XML-alternatives like JSON, Protocol Buffer could help you.