0

I would like to integrate this caching mechanism in my app: Using DiskLruCache in android 4.0 does not provide for openCache method

Now, when I have the bitmap, which key shall I use? Or better: How can I generate a key?

It would be good if I could generate the key from the bitmap itself so that I can later call contains(String key) to check whether the bitmap is already in the cache.

So what can I do?

Community
  • 1
  • 1
user2426316
  • 7,131
  • 20
  • 52
  • 83

1 Answers1

0

You want to generate the key by hashing the Bitmap bytes, ensuring to a high probability that no two Bitmaps will result in the same key, unless they are identical.

You will need to convert your Bitmap into a byte array to use the built-in MessageDigest library.

Bitmap bmp = new Bitmap(); // load your bitmap...
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

MessageDigest digest = MessageDigest.getInstance("SHA-256");  
digest.update(byteArray);
byte[] keyBytes = digest.digest(byteArray);

Afterwards, convert the key bytes into a string with a Bytes to Hex function like this one.

Community
  • 1
  • 1
Autumn
  • 91
  • 1