Link to home
Start Free TrialLog in
Avatar of Dermofit
Dermofit

asked on

How to save an image in J2ME

I have an edited image on an Image object.

How o I save that image to the cellphone's memory card? I don't care what format. Any will do (png, jpg, gif, etc).
Avatar of CodeFish
CodeFish
Flag of Canada image

You should look at the FileConnection API:
http://developers.sun.com/mobility/apis/articles/fileconnection/
http://developers.sun.com/mobility/apis/ttips/fileconnection/

You need to save/load the image via byte streams.

This example loads an image from over the network:
http://www.java2s.com/Code/Java/J2ME/ImageLoader.htm

The principles are the same, but instead of HttpConnection you want to use FileConnection.

I haven't tried it, but this looks promising:
http://ce.sharif.edu/~p_amini/j2me/JPEG_Encoder
The code is difficult to follow, but it may help.

I tried to rework this code found at http://www.coderanch.com/t/229101/Java-Micro-Edition/java/jme-upload-image-file-captured but haven't enough time/expertise to get it running:
FileConnection fileConn =(FileConnection)onnector.open "file:///root1/111429594531243BD9-0.jpg", Connector.READ);// file://root1/ is default path for wtk emuluator for other device u need to find the path
InputStream fis = fileConn.openInputStream();// open input stream
//InputStreamReader fisr = null;
byte[] readData = null;
long overallSize = fileConn.fileSize();
if ( overallSize > 0 ) {
readData = new byte[(int)overallSize];
int bytesRead = 0;
int chunckSize = 512;
while (bytesRead < overallSize) {
int chunck = chunckSize;
if ( (overallSize - bytesRead) < chunckSize )
{
chunck = (int)(overallSize - bytesRead);
}
int count = fis.read(readData, bytesRead, chunck);
if ( count > 0 )
{
bytesRead += count;
}
 
}
imageData = readData;
}
System.out.println("imageData"+imageData); 

Open in new window

Let me know what progress you do/don't make with this. I haven't done it so it would be good to know.
Thanks

Also,
file:///root1/ is the temp directory where the image needs to be located when testing with emulator.
when you run the emulator you will see an output line in the console that indicates where your "storage root" is located.
What I do is start the emulator, but before launching the Midlet navigate to the temp directory and drop the image file in. I don't know of a better/automatic way to have the image generated in the temp directory.
ASKER CERTIFIED SOLUTION
Avatar of CodeFish
CodeFish
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can use a single fileconnection on multiple files and/or create the file if it does not exist as follows:

      fc = (FileConnection)Connector.open("file:///root1/saved.PNG");
      if(!fc.exists()){
          fc.create();
      }