Search code examples
androidfile-iobitmapserializablefileoutputstream

Can Bitmaps be written to cache using ObjectOutputStream?


I have a method called loadFromCache and it returns a bitmap if it is found in the cache. Long story short I have it narrowed down to this method, returning null at the end if the try/catch fails.

FileInputStream fis = new FileInputStream(getCacheDir()+(""+position));
        ObjectInputStream ois = new ObjectInputStream(fis);
        Bitmap temp = (Bitmap)ois.readObject();
        fis.close();
        return temp;

I have previously tried the Bitmap.compress(...) methods to save bitmaps but they were a little slow for my needs... Yes the bitmap has been written to these positions, but I don't know if it (Bitmap) is serializable so is it actually saving? And yes I remembered to flush when I wrote the file.


Solution

  • How is Bitmap.compress() too slow for you? The only faster(?) way would be to write the bitmap unchanged to disk, see below.

    Using MappedByteBuffer together with Bitmap.copyPixelsToBuffer() may work. I haven't tested this but it seems like it could work. Note that you most likely will have to store image dimensions yourself.