Posts Tagged 'jpeg'

How to save Jpeg files in the Android emulator

I am learning the basics of graphics in Android. I started with the Fingerpaint activity in Api Demos. What I wanted to learn:

  • how to turn a view into a jpeg (jpg) file
  • how to save that on an Android device
  • how to set the background of a view from an image

So far I have something working on the emulator. I have not tried it yet on a real device.

1. Create an Android Virtual Device (avd) and assign a value for SD card memory. The figure below  shows an assignment of 128MB.

AVD details with SD card memory

2. Give permission to your application so it is allowed to write to external storage. Edit the manifest file AndroidManifest.xml. Add uses-permission as the first item in the manifest element.

<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”>
</uses-permission>

3. In the activity and view code, create files and folders. (See below for attached source code.)

File myDir=new File("/sdcard/saved_images");
 myDir.mkdirs();
 mImageCount++;
 String fname = "image-" + mImageCount + ".jpg";
 File file = new File (myDir, fname);
 if (file.exists ()) file.delete ();
 mView.saveAsJpg (file);
...

public void saveAsJpg (File f) {
String fname = f.getAbsolutePath ();
FileOutputStream fos = null;
try {
fos = new FileOutputStream (f);
// Take the bitmap of the view and write it out as a jpeg.
mBitmap.compress (CompressFormat.JPEG, 95, fos);
} catch (Throwable ex) {

}

} // end saveAsJpg

4. Run your application and draw something on the screen. Then use the “save” menu item to save your file.

5. To see the file that you created, you have to open the DDMS window in Eclipse while the emulator is running. If you go the “File Explorer” tab and look in the /mnt/sdcard folder. If you actually want the file, you use the little icon to the right of the tabs. Click the “Pull a file from device” after you highlight the file in the file list.

Where To Find The Code

The Eclipse project for this can be found here: download zip file. If you find that the app does not build in Eclipse, be sure to do a clean build by using the “Clean” item on the Project menu.

When running in the emulator, it should look like this:

About This Work
This work was done on a Macbook with Eclipse Galileo and Android version 2.2. In Eclipse, when you list “installation details” under “About Eclipse” it shows version 0.9.9.v201009221407-60953 of the Android Developer Tools.



Follow

Get every new post delivered to your Inbox.

Join 72 other followers