Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Revision as of 13:26, 3 June 2009 by jarmlaht (Talk | contribs)

How to read an image from Gallery in Java ME

From Wiki
Jump to: navigation, search


This article shows, how to read an image from Gallery by using FileConnection API (JSR-75) and show it on Form. The Gallery folders can be accessed by using system properties, for example: System.getProperty(""). File contents are read by using InputStream, data is saved to a byte array and Image object is created by using Image.createImage() method.

The full source code for a test MIDlet:

Source code:

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
public class ReadMIDlet extends MIDlet implements CommandListener {
private Form form;
private String photos = "";
private Image image;
private Command exitCommand;
public void startApp() {
form = new Form("ReadMIDlet");
exitCommand = new Command("Exit", Command.EXIT, 1);
String path = System.getProperty(photos); // for example: file:///C:/Data/Images/
form.append("path = " + path);
// An image "image.png" must be in the folder shown above
image = readFile(path + "image.png");
if (image != null) form.append(image);
else form.append("Image not found!");
public void pauseApp() {
public void destroyApp(boolean unconditional) {
public Image readFile(String path) {
try {
FileConnection fc = (FileConnection), Connector.READ);
if(!fc.exists()) {
System.out.println("File doesn't exist!");
else {
int size = (int)fc.fileSize();
InputStream is = fc.openInputStream();
byte bytes[] = new byte[size];, 0, size);
image = Image.createImage(bytes, 0, size);
} catch (IOException ioe) {
System.out.println("IOException: "+ioe.getMessage());
} catch (IllegalArgumentException iae) {
System.out.println("IllegalArgumentException: "+iae.getMessage());
return image;
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) this.notifyDestroyed();

See also

87 page views in the last 30 days.