David Marko on THINGS around …

Christianity, development and life …

Archive for the ‘development’ Category

Need to convert images (stored as an attachments on Lotus Notes documents) into text to be serializable via JSON ?

leave a comment »

We have had recently a special requirement … we needed to serve JSON product data (from Lotus Notes database product catalogue) with images embedded inside. JSON is generally textual format so we have to find out the way how to embed the binary image there. Fortunately we are using xPages here so we can use JAVA libraries that are plenty available for many different use cases …

For a few year we are successfully using JODD Library as a JAVA coders helper tool for our xPages applications. Before JODD library being started used in our company we were using Apache Commons libraries but we have had many problems with JAVA permissions issues in Domino in many situations. To solve this we tried to use JODD library and never turned back … Its amazing project that can help xPages developer in many areas. JODD contains well balanced helper objects covering many daily use cases in web development. What’s more JODD comes with very nice managed documentation and examples that are really necessary for adopting the library. (see yourself here http://jodd.org )

Complete commented code covering our requirements is below ….

import java.io.IOException;

import jodd.io.StreamUtil;
import jodd.util.Base64;

import lotus.domino.Document;
import lotus.domino.EmbeddedObject;
import lotus.domino.NotesException;

public class Base64Converter {

	public Base64Converter() {
	}

	// simple static method that returns image attachment as a text base encoded ...
	private static String getImageAsString(Document cdoc, String attachmentName) throws NotesException{
		String imageAsString="";

		// getting the EmbeddedObject = attachment from document
		EmbeddedObject file = cdoc.getAttachment(attachmentName);

		if (file!=null){
			try {
				// we need to transform our file attachment ...
				// ... (JPEG image in our case) to byte[] object first
				// we use the JODD library StreamUtil.readBytes method here
				byte[] bytes = StreamUtil.readBytes(file.getInputStream());

				// encoding to base64 text representation goes here using JODD library tools
				// so we get text representation of our image
				imageAsString=Base64.encodeToString(bytes);

			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return imageAsString;
	}
}

Advertisements

Written by David Marko

February 9, 2013 at 6:17 pm

Posted in development

Tagged with , ,