Externalizing Resources - Persisting Images in RMS-ImageRmsUtils

来源:互联网 发布:昆明暴恐 不反抗 知乎 编辑:程序博客网 时间:2024/06/08 15:33

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 the technical tip Obfuscating Your MIDlet Suite 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 format for each record is as follows:

RMS RecordStore record format used by ImageRmsUtils

 

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.

A close look at ImageRmsUtils.java

Below is ImageRmsUtils.java, which 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.

Class ImageRmsUtils
/*
* 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:

Using Class ImageRmsUtils - Saving an Image
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

In this article I've 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.

Acknowledgments

I want to thank Ariel Levin of Sun Microsystems for reviewing this technical tip and providing technical feedback.