Your Ad Here

Wednesday, June 8, 2011

How to write Binary data in XML

Binary data in XML

Sometimes It is required that we need to send content / binary data in xml itself instead of urls / path along with the meta data of the content.

Here is the code to write an Image File in XML : (I used here Base64 encoding)

-----------------------------------------------------------------------------------
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;


public class WriteBinaryXML {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            BufferedImage img = ImageIO.read(new File("/pathofsourceimage/image.jpg"));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(img, "jpg", baos);
            baos.flush();
            String encodedImage = new Base64().encodeToString(baos.toByteArray());
            baos.close();
            System.out.println("encodedImage -----  " + encodedImage);
 
    // Write this String (encodedImage)  to the tag using any xml api.

          }
    }
}

No comments:

Post a Comment