Can Universal image loader for android work with images from sqlite db?

android, database, sqlite, universal-image-loader

Solution

UIL doesn't support of images from SQLite DB out of the box. But you can add this support yourself, you just need come up with new scheme/protocol name (e.g. db://), implement own `ImageDownloader` and set it to configuration.

For example:

Lets choose own scheme `db` so our URIs will look like "db://...".

Then implement `ImageDownloader`. We should catch URIs with our scheme, parse it, find needed data in DB and create `InputStream` for it (it can be `ByteArrayInputStream`).

public class SqliteImageDownloader extends BaseImageDownloader {

    private static final String SCHEME_DB = "db";
    private static final String DB_URI_PREFIX = SCHEME_DB + "://";

    public SqliteImageDownloader(Context context) {
        super(context);
    }

    @Override
    protected InputStream getStreamFromOtherSource(String imageUri, Object extra) throws IOException {
        if (imageUri.startsWith(DB_URI_PREFIX)) {
            String path = imageUri.substring(DB_URI_PREFIX.length());

            // Your logic to retreive needed data from DB
            byte[] imageData = ...;

            return new ByteArrayInputStream(imageData);
        } else {
            return super.getStreamFromOtherSource(imageUri, extra);
        }
    }
}

Then we set this `ImageLoader` to configuration:

ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
        ...
        .imageDownloader(new SqliteImageDownloader(context))
        .build();

ImageLoader.getInstance().init(config);

And then we can do following to display image from DB:

imageLoader.displayImage("db://mytable/13", imageView);

Problem

I would like to store my images in an sqlite db, in blob-s, and maybe encrypt them. Is it possible to use the Android-Universal-Image-Loader with images from an sqlite database?

Original source