Last active
April 19, 2018 17:53
-
-
Save eviltak/1b3762dc0c919e85ba8d21c8d151d80d to your computer and use it in GitHub Desktop.
A hard disk cache for storing Bitmaps in Xamarin.Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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