Externalizing Resources - Persisting Images in RMS

by C. Enrique Ortiz

If you are encountering size restrictions when provisioning your MIDlet, you have a couple of options to consider. One of the options, using obfuscation to reduce the application size, was previously covered in another technical tip, Obfuscating Your MIDlet Suite. This tech tip explains externalizing resources by saving resources into the Record Management System (RMS).

Storing Images in RMS

RMS is a simple but effective local storage subsystem. It provides the basic methods to open, manage, share, and search RecordStores, and write and read records. For more information about the RMS API, please refer to the MIDP Javadoc.

The utility class ImageRmsUtils explained in this article uses RMS to store the individual images, with one image per record. The record format for each record is as follows:

Image of RMS RecordStore record format

Each record holds all the information that describes an individual image: the image name, width, height, length, the image raw bytes, and creation time stamp. With this information ImageRmsUtils can manage the image local store. Note that RMS record stores can be shared across MIDlets, and sharing the image local store across MIDlets will further save additional space on the handset. The next listing shows class ImageRmsUtils.

The following ImageRmsUtils.java class contains methods to store and load images to and from RMS, as well as methods to clear images older than a specified amount of time expire, and to completely clear the image RMS record store.

/\*
 \* ImageRmsUtils.java
 \*
 \* Contains methods to store and load Images to/from RMS,
 \* expire images, and clear the RMS local store.
 \*/

package com.cenriqueortiz.ttips.utils;

import javax.microedition.lcdui.\*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

/\*\*
 \* ImageRmsUtils
 \*
 \* Implements methods to store and load Images to/from RMS,
 \* expire images, and clear the RMS local store.
 \*
 \* @author C. Enrique Ortiz
 \*/
public final class ImageRmsUtils {

    /\*\*
     \* Saves a PNG Image
     \*
     \* @param resourceName is the name of the PNG image to save.
     \* @param image the Image to save.
     \*/
    static public void savePngImage(String recordStore, String resourceName, Image image) {
        RecordStore imagesRS = null;
        int height, width;
        if (resourceName == null) return; // resource name is required

        // Calculate needed size and allocate buffer area
        height = image.getHeight();
        width = image.getWidth();

        int[] imgRgbData = new int[width\*height];

        try {
            image.getRGB(imgRgbData, 0, width, 0, 0, width, height);
            imagesRS = RecordStore.openRecordStore(recordStore, true);

            //
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(bout);
            //  Serialize the image name
            dout.writeUTF(resourceName);
            dout.writeInt(width);
            dout.writeInt(height);
            dout.writeLong(System.currentTimeMillis());
            dout.writeInt(imgRgbData.length);
            //  Serialize the image raw data
            for (int i=0; i<imgRgbData.length; i++) {
                dout.writeInt(imgRgbData[i]);
            }
            dout.flush();
            dout.close();
            byte[] data = bout.toByteArray();
            int recid = imagesRS.addRecord(data, 0, data.length);
        } catch (Exception e) {
            // Log the exception
        } finally {
            try {
                // Close the Record Store
                if (imagesRS != null) imagesRS.closeRecordStore();
            } catch (Exception ignore) {
                // Ignore
            }
        }
    }

    /\*\*
     \* Load image with specified name
     \*
     \* @param recordStore is the name of the record store.
     \* @param resourceName is the name of the image to load
     \*
     \* @return the loaded Image or null.
     \*/
    static public Image loadPngFromRMS(String recordStore, String resourceName) {
        RecordStore imagesRS = null;
        Image img = null;
        try {
            imagesRS = RecordStore.openRecordStore(recordStore, true);
            RecordEnumeration re = imagesRS.enumerateRecords(null, null, true);
            int numRecs = re.numRecords();
            // For each record
            for(int i=0; i<numRecs; i++) {
                // Get the next record's ID
                int recId = re.nextRecordId(); // throws InvalidRecordIDException
                // Get the record
                byte[] rec = imagesRS.getRecord(recId);
                //
                ByteArrayInputStream bin = new ByteArrayInputStream(rec);
                DataInputStream din = new DataInputStream(bin);
                String name = din.readUTF();
                // If this is the image we are looking for, load it.
                if (name.equals(resourceName)== false) continue;

                int width  = din.readInt();
                int height = din.readInt();
                long timestamp = din.readLong();
                int length = din.readInt();

                int[] rawImg = new int[width\*height];
                //  Serialize the image raw data
                for (i = 0; i < length; i++) {
                    rawImg[i] = din.readInt();
                }
                img = Image.createRGBImage(rawImg, width, height, false);
                din.close();
                bin.close();
            }
        } catch (InvalidRecordIDException ignore) {
            // End of enumeration, ignore
        } catch (Exception e) {
            // Log the exception
        } finally {
            try {
                // Close the Record Store
                if (imagesRS != null) imagesRS.closeRecordStore();
            } catch (Exception ignore) {
                // Ignore
            }
        }
        return img;
    }

    /\*\*
     \* Removes expired images from the cache
     \*
     \* @param recordStore is the name of the record store.
     \* @param number of seconds for the expiration
     \*
     \* @return the number of images expired.
     \*/
    static public int clearExpiredImages(String recordStore, int expireNumSeconds) {
        RecordStore imagesRS = null;
        int deletedRecs = 0;
        try {
            imagesRS = RecordStore.openRecordStore(recordStore, true);
            RecordEnumeration re = imagesRS.enumerateRecords(null, null, true);
            int numRecs = re.numRecords();
            // For each record
            for(int i=0; i<numRecs; i++) {
                // Get the next record's ID
                int recId = re.nextRecordId(); // throws InvalidRecordIDException
                // Get the record
                byte[] rec = imagesRS.getRecord(recId);
                ByteArrayInputStream bin = new ByteArrayInputStream(rec);
                DataInputStream din = new DataInputStream(bin);
                String name = din.readUTF();
                int width  = din.readInt();
                int height = din.readInt();
                long timestamp = din.readLong();

                // calculate expiration, and remove record if expired
                long now = System.currentTimeMillis();
                long delta = now - timestamp; // delta in milliseconds
                // Remove this record if it has expired.
                //  Convert delta mills to seconds prior to test.

                if ((delta/1000) > expireNumSeconds) {
                    imagesRS.deleteRecord(recId);
                    deletedRecs++;
                }
            }
        } catch (InvalidRecordIDException ignore) {
            // End of enumeration, ignore
        } catch (Exception e) {
            // Log the Exception
        } finally {
            try {
                // Close the Record Store
                if (imagesRS != null) imagesRS.closeRecordStore();
            } catch (Exception ignore) {
                // Ignore
            }
        }
        return deletedRecs;
    }

    /\*\*
     \* Clears the Images Cache, both storage and in-memory
     \*
     \* @param recordStore is the name of the record store.
     \*/
    static public void clearImageRecordStore(String recordStore) {
        try {
            RecordStore.deleteRecordStore(recordStore);
        } catch (Exception e) {
            // Log the Exception
        }
    }
}

Note that methods loadPngFromRMS() and clearExpiredImages() could have used a RecordFilter to find the records of interest. To keep the image RMS utilities small, the methods implemented the record searches themselves. This is cheaper than implementing two RMS record filters.

Using the ImageRmsUtils Utility Class

Using the ImageRmsUtils RMS image utility class is very simple. The utility class provides four public static methods to save and load an image to/from RMS, to clear images that have expired, and to completely clear the images local store:

  • void savePngImage(String recordStore, String resourceName, Image image)
  • Image loadPngFromRMS(String recordStore, String resourceName)
  • int clearExpiredImages(String recordStore, int expireNumSeconds)
  • void clearImageRecordStore(String recordStore)

Once an image has been retrieved, perhaps over the network, it can be stored in RMS. To store an image once it has been created, call method savePngImage(), providing as input the name of the record store, the name of the image, and the image itself:

private static final String IMAGE_RS = ...;
private String imgName = ...;
:

// Creates an immutable image.   
Image img = Image.createImage(...);

// Save PngImage into RMS. 
ImageRmsUtils.savePngImage(IMAGES_RS, imgName, img);

Loading an image from RMS is even simpler-just specify the name of the record store, and the name of the image to load:

Using Class ImageRmsUtils - Loading an Image
private static final String IMAGE_RS = ...;
private String imgName = ...;
:

Image img = ImageRmsUtils.loadPngFromRMS(IMAGES_RS, imgName);

To clear expired images from the record store call method clearExpiredImages(), passing as argument the name of the record store, and the time in seconds to use for expiration, any images older than the specified number of seconds will be deleted from the record store:

Using Class ImageRmsUtils - Expiring an Image
private static final String IMAGE_RS = ...;
private static final int EXPIRE_TIME_SECS_3DAYS = 60\*60\*24\*3; // 3 days
:

// Clear any image that is 3 days old, or older
int numDeletedRecs = ImageRmsUtils.clearExpiredImages(IMAGES_RS, EXPIRE_TIME_SECS_3DAYS);

To clear the image local store completely, call method clearImageRecordStore(), passing as argument the name of the record store to clear:

Using Class ImageRmsUtils - Clearing the Image Record Store
private static final String IMAGE_RS = ...;
:

clearImageRecordStore(IMAGE_RS);
Conclusion

This tech tip introduced the ImageRmsUtils helper class that you can use to save and load images to and from RMS. The utility class also provides methods to clear the image record store, and remove individual images that are older than a specified amount of time. You can use this utility class to separate resources from the MIDlet suite, and implement an image cache that can be shared across MIDlets, effectively helping reduce your MIDlet suite application size.

Comments:

The new code layouts are so hard to read. Please change it back to the old code layouts(which were cut-and-paste from Netbeans) ...

Posted by Thomas on December 20, 2007 at 12:09 PM PST #

Yes, I agree and we are working on it. Thank you for your patience.

Posted by Christine Dorffi on December 20, 2007 at 02:08 PM PST #

Hi,

That was a very good information about image storage. Can you please tell something more on the image size restrictiction which can be stored in the RMS.. Suppose i have images of say 500KB or more.. is it feasible to store the same and use...

Posted by Shrikant on March 25, 2008 at 02:30 PM PDT #

Shrikant, the device restrictions are device-specific. Refer to the handset specs for more information for the specific handsets.

ceo

Posted by Shrikant on March 26, 2008 at 02:10 PM PDT #

The response above to Shrikant's question was actually posted by the author, C. Enrique Ortiz. Thanks.

Posted by christine dorffi on March 27, 2008 at 03:46 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

Tips for developers who use Java technologies (Java SE, Java ME, JavaFX) for mobile and embedded devices.

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today