11

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.

2
  • I'm going to be entirely unhelpful, but: why? Why do you want to store images in XML? Is there a better way to do this? If I found myself in this situation, I would reconsider what I am doing and why. Aug 22, 2009 at 2:20
  • Hi Mike, it's a valid point - there possibly is a better way and I open to suggestions. The primary purpose of the XML document is to store information about a university. It keeps an array of campuses which in turn keep arrays of rooms. The images I'm storing are maps for the campuses. I figured that XML was probably the best way to store parent-child data. But please let me know if you have a better suggestion!
    – Hoopla
    Aug 22, 2009 at 12:43

10 Answers 10

20

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.

1
  • obrigado Joao! @JoaoSilva Aug 3, 2013 at 17:57
8

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)

1
  • Cheers mate, that's a much neater package!
    – Hoopla
    Aug 22, 2009 at 13:22
2

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>
2

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

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.

1
  • Thanks Michael, admittedly I was clutching as straws and copied someone's example of how to convert the array without really thinking about it. Now using Apaches Commons. Cheers for advice
    – Hoopla
    Aug 22, 2009 at 13:25
1

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.

1

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
0

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.

0

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();
0
node.setTextContent( base64.encodeAsString( fileBytes ) )

using org.apache.commons.codec.binary.Base64

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.