Skip to content

Instantly share code, notes, and snippets.

@eviltak
Last active April 19, 2018 17:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eviltak/1b3762dc0c919e85ba8d21c8d151d80d to your computer and use it in GitHub Desktop.
Save eviltak/1b3762dc0c919e85ba8d21c8d151d80d to your computer and use it in GitHub Desktop.
A hard disk cache for storing Bitmaps in Xamarin.Android
using System.Threading.Tasks;
using Android.Content;
using Android.Graphics;
using Java.IO;
namespace Android.Util.Graphics
{
public static class BitmapDiskCache
{
private const string Extension = @".fil";
public static File CacheDir { get; set; }
public static async void Add(string id, Bitmap bitmap)
{
byte[] data = await BitmapLoader.EncodeBitmap(bitmap);
File file = new File(CacheDir, id + Extension);
FileOutputStream os = new FileOutputStream(file);
try
{
await os.WriteAsync(data);
}
finally
{
os.Flush();
os.Close();
}
}
public static async Task<Bitmap> Get(string id)
{
File file = new File(CacheDir, id + Extension);
if (!file.Exists())
{
// Data doesn't exist
return null;
}
byte[] data = new byte[file.Length()];
FileInputStream inputStream = new FileInputStream(file);
try
{
await inputStream.ReadAsync(data);
}
finally
{
inputStream.Close();
}
return await BitmapLoader.DecodeBitmap(data);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment