Base64 ImageHandler

edited November 2013 in DevShare Downloads
If you are using the RE API to run reports in html you can write your own image handler. You can do this by extending the HTMLImageHandler class. For example to base64 encode the images and write this data into the image src tag, use a handler like:
//BTW No error checking is shown in this example

import org.apache.commons.codec.binary.Base64;
import org.eclipse.birt.report.engine.api.HTMLImageHandler;
import org.eclipse.birt.report.engine.api.IImage;
/**
 * Default implementation for writing images in a form that is used in a
 * web-application.
 */
public class MyB64ImageHandler extends HTMLImageHandler
{

    public MyB64ImageHandler( )
    {
    }

    public String onDesignImage( IImage image, Object context )
    {
        return handleImage( image, context, "design", true ); //$NON-NLS-1$
    }


    public String onDocImage( IImage image, Object context )
    {
        // TODO Auto-generated method stub
        return null;
    }

    public String onURLImage( IImage image, Object context )
    {
        assert ( image != null );
        String uri = image.getID( );
        if (uri.startsWith( "http:" ) || uri.startsWith( "https:" ))
        {
            return uri;
        }
        return handleImage( image, context, "uri", true ); //$NON-NLS-1$
    }


    public String onCustomImage( IImage image, Object context )
    {
        return handleImage( image, context, "custom", false ); //$NON-NLS-1$
    }

    public String onFileImage( IImage image, Object context )
    {
        return handleImage( image, context, "file", true ); //$NON-NLS-1$
    }


    protected String handleImage( IImage image, Object context, String prefix,
            boolean needMap )
    {
        String rtn = "no data";
        byte[] myimagedata = image.getImageData();
        String mt = "data:"+image.getMimeType()+";base64,";
        String encodedText = new String(Base64.encodeBase64(myimagedata));
        rtn = mt + encodedText;
        return rtn;
    }

    protected String getImageMapID( IImage image )
    {
        if ( image.getReportRunnable( ) != null )
        {
            return image.getReportRunnable( ).hashCode( ) + image.getID( );
        }
        return image.getID( );
    }

}


To set the image handler in the RE API use code similar to the following:



HTMLRenderOption options = new HTMLRenderOption();

options.setOutputFileName("output/resample/mytopnimage.html");

options.setImageHandler(new MyB64ImageHandler());



This should produce image tags with the base64 data included like:

<img id="__bookmark_1" src="data:image/png;base64,encodeddata
Sign In or Register to comment.