Externalizing Resources - Persisting Images in RMS-ImageRmsUtils

本文介绍了一个实用类ImageRmsUtils,可用于将图像存入和从记录管理系统(RMS)中读取,同时提供了清理过期图像及完全清除图像记录存储的方法。通过使用该类,可以有效地分离MIDlet套件资源并实现跨MIDlet共享的图像缓存。

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

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.

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.

 
**项目名称:** 基于Vue.js与Spring Cloud架构的博客系统设计与开发——微服务分布式应用实践 **项目概述:** 本项目为计算机科学与技术专业本科毕业设计成果,旨在设计并实现一个采用前后端分离架构的现代化博客平台。系统前端基于Vue.js框架构建,提供响应式用户界面;后端采用Spring Cloud微服务架构,通过服务拆分、注册发现、配置中心及网关路由等技术,构建高可用、易扩展的分布式应用体系。项目重点探讨微服务模式下的系统设计、服务治理、数据一致性及部署运维等关键问题,体现了分布式系统在Web应用中的实践价值。 **技术架构:** 1. **前端技术栈:** Vue.js 2.x、Vue Router、Vuex、Element UI、Axios 2. **后端技术栈:** Spring Boot 2.x、Spring Cloud (Eureka/Nacos、Feign/OpenFeign、Ribbon、Hystrix、Zuul/Gateway、Config) 3. **数据存储:** MySQL 8.0(主数据存储)、Redis(缓存与会话管理) 4. **服务通信:** RESTful API、消息队列(可选RabbitMQ/Kafka) 5. **部署与运维:** Docker容器化、Jenkins持续集成、Nginx负载均衡 **核心功能模块:** - 用户管理:注册登录、权限控制、个人中心 - 文章管理:富文本编辑、分类标签、发布审核、评论互动 - 内容展示:首页推荐、分类检索、全文搜索、热门排行 - 系统管理:后台仪表盘、用户与内容监控、日志审计 - 微服务治理:服务健康检测、动态配置更新、熔断降级策略 **设计特点:** 1. **架构解耦:** 前后端完全分离,通过API网关统一接入,支持独立开发与部署。 2. **服务拆分:** 按业务域划分为用户服务、文章服务、评论服务、文件服务等独立微服务。 3. **高可用设计:** 采用服务注册发现机制,配合负载均衡与熔断器,提升系统容错能力。 4. **可扩展性:** 模块化设计支持横向扩展,配置中心实现运行时动态调整。 **项目成果:** 完成了一个具备完整博客功能、具备微服务典型特征的分布式系统原型,通过容器化部署验证了多服务协同运行的可行性,为云原生应用开发提供了实践参考。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值