6

I am trying to use the AndroidImageSlider library and populate it with images that I have downloaded as a base64 string.

The library only accepts URLs, R.drawable values, and the File object as parameters.

I am trying to convert the image string to a File object in order to be passed to the library function. I have been able to decode from base_64 and convert to a byte[] so far.

String imageData;
byte[] imgBytesData = android.util.Base64.decode(imageData, android.util.Base64.DEFAULT);
  • 1
    I think it's probably better to create the file using `FileOutputStream` then serve it from a restful URL on the server. Assuming the image data is already in the format you want, just need to write the data to the file. See this SO thread: http://stackoverflow.com/questions/20879639/write-base64-encoded-image-to-file – DrewT May 02 '15 at 18:32
  • But if I was to create a `FileOutputStream`, how am I supposed to access a File object? The library specifically wants the File parameter, is there something more to the `FileOutputStream`? –  May 02 '15 at 18:35
  • 1
    just serve from restful url after writing the image to a file. anyhow seems like you got it fixed nice! – DrewT May 02 '15 at 23:05

1 Answers1

10

You'll need to save the File object to disk for that to work. This method will save the imageData string to disk and return the associated File object.

public static File saveImage(final Context context, final String imageData) {
    final byte[] imgBytesData = android.util.Base64.decode(imageData,
            android.util.Base64.DEFAULT);

    final File file = File.createTempFile("image", null, context.getCacheDir());
    final FileOutputStream fileOutputStream;
    try {
        fileOutputStream = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    }

    final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
            fileOutputStream);
    try {
        bufferedOutputStream.write(imgBytesData);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            bufferedOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file;
}

It creates a temporary file in your applications 'cache' directory. However, you are still responsible for deleting the file once you no longer need it.

pathfinderelite
  • 3,047
  • 1
  • 27
  • 30