Namespaces
Variants
Actions

How to read an image from Gallery in Java ME

Jump to: navigation, search
SignpostIcon FilmReel 52.png
Article Metadata

Tested with
Compatibility
Platform(s): Series 40 6th Edition SDK, Nokia SDK 1.0 for Java, Nokia SDK 1.1 for Java, Nokia SDK 2.0 for Java (beta)

Article
Created: jarmlaht (15 Feb 2008)
Last edited: jumantyn (30 Jul 2012)

Overview

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("fileconn.dir.photos"). 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: ReadMIDlet.java

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;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.Connector;
import java.io.InputStream;
import java.io.IOException;
 
public class ReadMIDlet extends MIDlet implements CommandListener {
private Form form;
private String photos = "fileconn.dir.photos";
private Image image;
private Command exitCommand;
 
public void startApp() {
form = new Form("ReadMIDlet");
exitCommand = new Command("Exit", Command.EXIT, 1);
form.addCommand(exitCommand);
form.setCommandListener(this);
Display.getDisplay(this).setCurrent(form);
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.open(path, 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];
is.read(bytes, 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

This page was last modified on 30 July 2012, at 09:09.
377 page views in the last 30 days.
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.

京ICP备05048969号  © Copyright Nokia 2013 All rights reserved