Learn To Save and Load External Images in Google Android

Written by:  • Edited by: Rebecca Scudder
Published Feb 15, 2010
• Related Guides: Android

In this article, we will see how to load a Image from an SD card to our Android project and show how to save it from our project to the SD card.

Introduction

This article is a complement to the How to Program the Android Camera to Take Pictures. Now let's have a look at two basic functions we can use when we are working with media files: Loading images from the SD card, and Saving images to the SD card.

The scenarios are the following:

We have an image in our SD card, placed in our application folder, and we want to use it in our Android project as a background, for example. In the “Load Images” paragraph we will cover this case.

In the other case we have taken a picture (as I explained in the How to Program the Android Camera to Take Pictures tutorial) and we want to save it to the SD card. The “Saving images” paragraph will cover this.

Loading Images

First of all, let's “set the environment”:

We have our image in the path /sdcard/myImages/myImage.jpg and we want to put it as a background in a layout. The layout structure is not important, just keep in mind that it is a

<LinearLayout>

<ImageView id=”imageToShow”>

</LinearLayout>

Let's begin!

To check if the file exists, let's do first a little confirmation: We need to create a File object with our image. We can do this using the following piece of code:

File imageFile = new File(“/sdcard/myImages/myImage.jpg”);

Tip! In my point of view, it's important to check everything we do. In this case, after we start working with the imageFile object we should assure ourselves that it exists. Something like

if(imageFile.exists()){

go on....

}

Now, let's create a Bitmap object from our image path.

Bitmap myBitmap = BitmapFactory.decodeFile(“/sdcard/myImages/myImage.jpg”);

Here, we have the image stored in a bitmap object in our android code. Let's place this image as background in your imageview in the layout. To do this, we need to create a ImageView android object linked to the XML.

ImageView myImage = (ImageView) findViewById(R.id.imageToShow);

And set the bitmap to this ImageView:

myImage.setImageBitmap(myBitmap);

It is that easy!

Hint! This code has to be placed in an activity, and this activity must have a

setContentView(R.layout.my_layout);

Otherwise, it won't work.

Saving Images

Now we'll look at the case where we take a picture with the camera using the 'How to Program the Android Camera to Take Pictures' tutorial. When we take a picture, we receive a byte array... what do we do with this? How can we convert this to a image in our SD card? Let's do it.

We create a File object with the place where to store the images.

File sdImageMainDirectory = "/sdcard/myImages";

We initialize some variables.

FileOutputStream fileOutputStream = null;

The image file name

String nameFile = “myImage”

Now, the quality of the image. This is a value between 0 and 100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting (via Google Android Reference)

int quality = 50;

We create the options we are going to use in our compression (adding the sample size)

BitmapFactory.Options options=new BitmapFactory.Options();

options.inSampleSize = 5;

We create the Bitmap from the imageData (byte array) and we throw it to the FileOutputStream with the name and the compression given (In this case JPEG)

Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,imageData.length,options);

fileOutputStream = new FileOutputStream(sdImageMainDirectory.toString() +"/" + nameFile + ".jpg");

BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);

myImage.compress(CompressFormat.JPEG, quality, bos);

bos.flush();

bos.close();

At this point, we will have the image stored in our SD card. Here we can play with the quality and sample values. How will the image look like with different values? You can try...

This is the core functionality, but the full source code can be found in my Code Snippets.

Ask, comment, interact!

Ask any question you have about this article, and I will try to answer as fast as I can. Comment my code, my writing; maybe there is something that it is missing or is not complete, just let me know!! In other words, interact!!

Follow up

If you want to know when new articles are released, subscribe yourself to the Google Android RSS. Otherwise, you can follow my research, articles and work in my professional twitter: jbeerdev


Comments

Showing all 39 comments
 
tekia Jun 9, 2011 7:41 AM
image
firstly i want to say i m sorry my english is not good enough. i don t want to save image in sd card. i want to use it in app.For example i take photo and i want to see image on the screen.how can i do this?i hope you can understand me.
Anonymous May 19, 2011 5:06 AM
save an image in gallery
i want to save the image in my gallery after editing from image editor
cyperton Apr 13, 2011 6:07 AM
RE: Learn To Save and Load External Images in google Android
Hi. I come from Thailand.
Jbeerdev .... Thanks you so much.. for your article...

If I want to save images after take picture to device(computer(NB)) . not sd card.
What should I do?
Please tell me please.....

Thanks.
Jbeerdev Mar 30, 2011 3:49 AM
RE: Learn To Save and Load External Images in Google Android
To get the application folder try the following code:

theContext.getApplicationInfo().dataDir

this will give you the path:

/data/data/your.app.package

This way you can retrieve images from the place you want.
kishore Mar 29, 2011 12:14 AM
get images dynamically
How to display images from a folder dynamically, like pictures stored in application data directory "/data/data/com.packagename/images/".
Anonymous Mar 20, 2011 8:34 PM
bitmap
I want to pass a bitmap object from one activity to another. Which is the efficient way of doing it?
1: Store the bitmap in a file in activity1 and read the stored bitmap in file from activity2?
2: pass bitmap from activity1 to activity2 using extras?
Any help regarding the same is appreciated
Ruturaj Jan 31, 2011 5:27 AM
Wonderful
Hi Jbeerdev, your tutorial worked wonder for me.... Thanx n keep it up! CHEERS...!!!
Naveen Dec 23, 2010 1:00 AM
Camera
Generating exception no data saving

PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//code added
String nameFile = "myImage";
String sdImageMainDirectory = "/sdcard/myImages";
//String nameFile = "myImage";
int quality = 50;
BitmapFactory.Options options=new BitmapFactory.Options();

options.inSampleSize = 5;
Bitmap myImage = BitmapFactory.decodeByteArray(data, 0,data.length,options);
Log.i("My image data is ",""+myImage);

FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(sdImageMainDirectory.toString() +"/" + nameFile + ".jpg");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);

// Log.i("My image data is ",""+bos);
myImage.compress(CompressFormat.JPEG, quality, bos);

try {
bos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Aijaz Ali Dec 18, 2010 4:30 AM
Salam
dear as I have done the web camera live preview in my emulator and I have also written the callbacks to capture image, but the problem is that I want to save the captured image in my project's drawable directory or on sdcard.
If you have any idea then please tell me....
johnf1_coolguy Sep 28, 2010 10:21 AM
Always returns null
Hi,

Thanks for tutorial,
The above code was very useful..

But im facing a problem in that,i.e particularly in this line
"fileOutputStream = new FileOutputStream(sdImageMainDirectory.toString() +"/" + nameFile + ".jpg");"

I think so the problem in that there is no file that exists in the name of "myname.jpg"

Please help me out...
Surendra Sep 8, 2010 3:05 AM
Need browse from gallery
Hi,
I want browse image from gallery and load into image viewer. Any idea welcome
Sab Aug 16, 2010 7:41 AM
save a camera picture in .bmp
Hi JBeer and thanks you a lot for all your tutorials, it's really useful for what I want to do.

You show us how save a camera picture in .jpg, but is it possible to do this in .bmp? And if it's possible, how?

Thanks for your answer.

I have tried this but it doesn't work very well (the picture quality is horrible) :

Camera.PictureCallback myPictureCallbackJpeg = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera c) {
//racine de la sdcard
File sdDir = Environment.getExternalStorageDirectory();
String pathSdDir = sdDir.getPath();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(pathSdDir + "/myDir/myPicture.bmp");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
try {
bos.write(data);
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}
};
Jbeerdev Aug 15, 2010 4:48 PM
RE: Learn To Save and Load External Images in Google Android
Hi dan.

You came from C/C++, aren't you? ;)

so, memory pool... explain yourself ta bit better. What do you need? store the image in a byte array, for example? this way it will be "in memory" and you can use it in other places.
dan Aug 15, 2010 9:28 AM
How to load the image in an mem pool
Hi Jbeer,
I was wondering if you have a some code the shows how to load the jpg image in a memory pool.

Thx
Jbeerdev Aug 3, 2010 3:59 AM
RE: Learn To Save and Load External Images in Google Android
Hi!

You can do de following:

Create a "File" object with the image that should be in the SDcard

File imageFile = new File(“/sdcard/myImages/myImageName.jpg”);

and then, check if the File object exists.

if(imageFile.exists()){

go on....

}

Hope it helps.
Noelle Aug 3, 2010 3:52 AM
hi
how to check if the image is in the sdcard alr? after doing the code.
Jbeerdev Aug 3, 2010 3:26 AM
RE: Learn To Save and Load External Images in Google Android
Hi Noelle

The code you have here:

http://snippets.dzone.com/posts/show/8685

I have placed in a class, as if it were an API. You have just to use it form "outside".
Noelle Aug 3, 2010 2:51 AM
Hi
you have to cre8 a new classfile for this before starting right? sorry im very new to android app and ive been trying to insert images into the sdcard!
mala May 20, 2010 1:28 AM
how to save data from sdcard to phone
Hello Jbeer,
I have done the storing data from phone to sdcard .
Now how can I retrievs does from sdcard to phone.
Meansfor example:: How can I store my contacts from the sd card to the phone's contactlist..
Please help

Thanks
Mala
Todd May 19, 2010 8:55 AM
RE: Always returns null
Jen,

I couldn't figure out why I was getting null, but I found that using BitmapFactory.decodeStream(InputFileStream) worked.

I also was able to get decodeFile() to work if I first copied the file to the app's data dir on the phone. This isn't ideal because of the processing time, but it did work.

Hope this helps.

(btw: this pertains to Incredible & Desire, I haven't encountered these issues on other devices)
Jen May 18, 2010 1:15 PM
Always returns null
I have a similar problem as Todd. I'm trying to use BitmapFactory to decode a byte array, but it always returns null, and I can't figure out why, or even a way to make it be more verbose about why it can't decode. Any help with this? Below is a snippet of my code.
(imageAsBytes is passed into the method as a parameter, and it is not null).

Bitmap image = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
Todd May 13, 2010 1:28 PM
BitmapFactory.decodeFile() returns null
Hi,

I've been using similar code as described in the post for a while. However with the release of the Incredible & Desire my users with those devices are unable to display images. BitmapFactory.decodeFile(pathAndFileName) always returns null. I've tried many different variations but with no luck.

Has anyone else encountered this issue, or have any idea how to correct it?

Thanks.
liberte May 13, 2010 8:14 AM
Load Images
Hi Jbeer!
I have problem with loading images:(
Could you please post the full code for loading images, it would be very helpful for me.
I have used your code for taking/saving pictures and everything works perfectly!
mala May 6, 2010 6:54 AM
save in SDCard
Hi Jbeer
Thanks a lot. I have done it. Your code becomes very useful for me.. THe change that I have done is that.. Instead of the follwing code :
InputStream is = this.getInstrumentation().getContext
().getAssets().open(filename);
I used
InputStream is = this.openFileInput(file name);

Thats all
Mala May 5, 2010 8:34 AM
save in SDCard
hi Jbeer,
Thanks a lot for your quick reply. I create the file.But problem occurs when I want to see the file in sdcard... Error is that no memory in the sdcard...
I created the avd with sdcard with 512M. still the error is coming
please guide me to see the file in sdcard..
Jbeerdev May 4, 2010 5:10 AM
RE: Learn To Save and Load External Images in Google Android
Hi Mala

Saving files in Android is the same as in Java. You can try this:

public void saveFile(String filename) throws Exception{
InputStream is = this.getInstrumentation().getContext
().getAssets().open(filename);
File directory = new File
(Environment.getExternalStorageDirectory().getPath()+"/myFiles");
if (!directory.exists()) {
directory.mkdir();
}
File file = new File(directory.getPath()+"/"+filename);
if (!file.exists() && directory.exists()){
try {
file.createNewFile();
} catch (IOException e) {
Log.d(TAG,"File creation failed for " + file);
}
}
if (file.exists() && file.canWrite()){
FileOutputStream os = new FileOutputStream(file);
byte[] b = new byte[1024];
int len;
while ((len = is.read(b))>0){
os.write(b,0,len);
}
os.flush();
os.close();
is.close();
}
else {
Log.e(TAG, "Failed to write the file to SDCard");
}
}

Don't forget to put the WRITE_EXTERNAL_STORAGE permission on the Manifest.

"filename" variable can be "text.txt" .
mala May 4, 2010 4:58 AM
how to save a text file in sdcard
I want to store a text file in sdcard .. How can I? are there any specific extension for the text file?why we are using every time the.img file? please help me.
Jbeerdev Apr 27, 2010 10:29 AM
RE: Learn To Save and Load External Images in Google Android
Hi Olof

Maybe you can do it by hand. I have not found a way to do it programmatically.
Olof Apr 26, 2010 5:36 AM
Dynamic compression when saving
Hi,

thanks for a good tutorial.
I would like to ask if there is any way to save a file and specify the target file size and lettign android use the appropriate compression?
abc Apr 21, 2010 5:58 PM
Showing android images in imageview
Create a imageview

<ImageView android:id="@+id/PartImage" </ImageView>

Use a drawable item ( jpg, png etc )
ImageView PartImage = (ImageView) findViewById(R.id.PartImage);
Drawable image = Drawable.createFromPath("/sdcard/front_wheel_car.jpg");
if ( image != null )
{
PartImage.setImageDrawable(image);
}
NavPEC Apr 12, 2010 8:19 AM
Calling an activity from within itself
Hi..
I am working on Camera Application In Android. (working in Emulator).

I have successfully coded the Camera.
Now i want that After taking the picture and waiting for another 5 sec.. the Camera Preview should start again.

This means i want to rerun the application from the code itself. How can this be done>
Please Help...

NavPEC
Antonia Apr 9, 2010 10:08 AM
Saving Problems
Hello Jbeer! Yes of course I could share it .. but it`s YOUR code :P
this is from the FileUtilities.java class


public static boolean ConvertByteArrayToImage(Context mContext, byte[] imageData,
int quality, String expName){

File filepath = new File("/sdcard/mydir");

if(!filepath.exists())
filepath.mkdirs();

FileOutputStream fos = null;
String filename=expName;

try {

BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 5;

Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,
imageData.length,options);

fos = new FileOutputStream(filepath.toString() +"/" + filename + ".png");

BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.flush();
bos.close();

myImage.compress(CompressFormat.PNG, quality, bos);

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return true;
}
}

CameraView.java is the same as you posted a while ago :)

Thank you so much :P
Jbeerdev Apr 9, 2010 7:22 AM
RE: Learn To Save and Load External Images in Google Android
Hi NavPEC

Try search in this path of your emulator:

/data/data/your_project_package_structure/files/your_image.png

you can check this using the "file browser" system in the DDMS view in Eclipse.
navPEC Apr 9, 2010 7:19 AM
Saving Image into Gallery in EMULATOR
hi....
I am working on Android Emulator.
Can u please tell me the code for saving image captured into GALLERY.


Please reply asap
NavPEC Apr 9, 2010 7:14 AM
saving Images captured via Android Camera
hi..
I am working on Android Emulator.
My Camera Preview is working fine and is able to click picture.

Now in the picture callback method i have used ur code snippet..
can u please tell me where can i find this image in my sys ?? and what if i want to save it to Gallery ??
please reply asap..
Thanks
Jbeerdev Mar 28, 2010 1:51 PM
RE: Learn To Save and Load External Images in Google Android
Hola Antonia

Could you use the image in your application? How long is the image (in kbs)? It sounds like the application create the empty image. I have done this dozens of times. Could you share your code?
Antonia Mar 15, 2010 9:58 AM
Saving Problems
Hello Jbeer! Nice work you have here! I followed your code snippets for taking a picture and saving.. I am having some problems in the saving part, meaning that I can create my own directory in the sd card (File filepath = new File("/sdcard/mydir");) and save the picture , but i can not open it. When I connect the HTC Tattoo to the PC, there is MyImage.jpg, but when I am trying to open it with Windows Picture and Fax Viewer (for exemple) it says: No preview available.. Any clue? Gracias... Un saludo !
Jbeerdev Mar 12, 2010 3:07 AM
RE: Learn To Save and Load External Images in Google Android
Hi Haya

Well, you could try to play with the "File" object (the one with the folder where images are supposed to be). I think you can get a list of files inside the folder, and do a "for" or a "while" to search for your image.
Haya Mar 11, 2010 6:55 PM
another issue
thanks a lot
its really helpful
but I was wodering what if i dont know the name of the picture
for example i would like to load the image captured ?
 
blog comments powered by Disqus
Email to a friend