How to save / retrieve image in memory on android?

7

Hello, I have a Bytes Array which is a image from it, how can I save it in external memory and if there is no save in the internal memory of android? and then how can I be recovering that image?

I need to save in a place that these images do not appear in the gallery of the phone, only in the application.

    
asked by anonymous 16.12.2014 / 12:54

2 answers

4

Let's first write a method that checks for the SDCard and if it is possible to write to it:

public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

The method returns true if it is possible to write to SDCard or false if it does not exist or for some reason can not write to it. / p>

We need two methods to save byte [], one to save to internal memory and another to save to SDCard .

Save to internal memory:

public void saveArrayToInternalStorage(String fileName, byte[] imagem){
    try{
        FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
        fos.write(imagem);
        fos.close();
    }catch (IOException e) {
        Log.w("InternalStorage", "Error writing", e);
    }
}

Save to SDCard:

MediaStore does not see the images we will use getExternalFilesDir() to get the Path to SDCard.

public void saveArrayToSDCard(String fileName, bytes[] imagem){
    File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File file = new File(path, fileName);
    try{
        OutputStream os = new FileOutputStream(file);
        os.write(imagem);
        os.close()
    } catch (IOException e) {
        Log.w("ExternalStorage", "Error writing", e);
    }
}

How to use:

if(isExternalStorageWritable(){
   saveArrayToSDCard("nomeDaImagem", imagemEmBytes);
}else{
    saveArrayToInternalStorage("nomeDaImagem", imagemEmBytes);
}  

If the application is to run in versions prior to Android 4.4, you must obtain the WRITE_EXTERNAL_STORAGE permission, add the following to Manifest

<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
                     android:maxSdkVersion="18" />
    ...
</manifest>  

Note: Images recorded by these methods will be deleted when the application is uninstalled.

Source: Android Storage Options

    
16.12.2014 / 19:22
1

So I read in this SOEn topic limit is 1 MB, more than that you would have to use NDK.

In this same topic there is also another approach that uses sqlite4java .

Take a look, it may be useful.

    
16.12.2014 / 17:51