4

I've spent several hours trying to figure out how to do this. I've read post after post here on stackoverflow and the documentation.

I have a android.graphics.Bitmap object and I need to get it's md5 sum. At the point that I want to verify the sum it has not been saved to the file system. I've seen several ways of doing this for java.io.File objects. I just need a function that receives a Bitmap object and returns the hex md5 sum as a String.

This might have been addressed somewhere but if it has been I have been unable to understand it or deduce how to do it from it.

The less resource heavy the method is the better it is of course.

Bjorninn
  • 4,027
  • 4
  • 27
  • 39

2 Answers2

9

Get bitmap's bytes to calculate md5.

Bitmap bm = ... // your bitmap
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object   
byte[] bitmapBytes = baos.toByteArray();

So you have byte array now. You can find how to get md5 hash of byte array in android here.

Leonidos
  • 10,482
  • 2
  • 28
  • 37
  • This implementation seems to work, it at least gives me a String that looks legit. It's not giving me the same vale that I generated beforehand in python using the same images. I have a suspicion it might have something to do with timestamps or I need to generate it somehow differently in python. Thanks for the answer. – Bjorninn Mar 01 '13 at 14:28
  • 1
    You better get md5 of image's raw data, but not android's Bitmap. There is no garantie that android and python threats images the same way. – Leonidos Mar 01 '13 at 14:36
  • Any suggestions on getting the raw data from the Bitmap file? – Bjorninn Mar 01 '13 at 14:40
  • 1
    What is bitmap file? If it is an ordinary file then open it in binary mode and read all bytes. This byte array should be the same in python and android, so you'll get same hashes. – Leonidos Mar 01 '13 at 14:46
  • Here's my problem. I have no idea what all of this means. Bitmap isn't a File object so I can't use it in that way. What does it mean to open in binary mode? I receive the bitmap from server and Android automatically creates the file. Do I need to save it to the the phone and then open it from storage as a File in binary mode? Sorry but I feel so lost.... – Bjorninn Mar 01 '13 at 14:59
  • It's hard to say no seeing your code (android/phyton). Ask one more question and give us more details if you wont be able get same hashes. – Leonidos Mar 02 '13 at 18:04
0

I'm not Android developer, but I see in the API reference (http://developer.android.com/reference/android/graphics/Bitmap.html) that there are methods for:

  • getting size of the bitmap: getWidth, getHeight
  • getting the pixels as an array of integers: getPixels

So you could just create an array of needed size, then read all the pixels, and convert the array to byte[].

Then it should be not a problem to calculate md5 sum from it.

mateusz.fiolka
  • 3,032
  • 2
  • 23
  • 24