2014-11-14 2 views
0

인터넷에서 알 수없는 크기의 사진을 다운로드하고 마지막으로 다운로드 한 이미지와 비교하여 이미지가 변경되었는지 확인합니다.메모리 친화적 인 이미지 해시

이렇게하려면 이미지 해시를 계산하고 해당 해시를 기억합니다.

String currentContactHash = 
    ImageFunctions.getPictureMd5Hash(bitmapTmp, false, errorContactHash); 
String currentInputHash = 
    ImageFunctions.getPictureMd5Hash(bitmapToUse, true, errorInputHash); 

이 가끔 웹에서 이미지의 크기를 제어 할 수 없습니다 ... 때문에 OutOfMemoryError 실패,하지만 난 그것의 해시를해야합니다. 여기

은 내 ImageFunctions :

public static byte[] convertImageToByteArray(Bitmap bitmap, boolean compress) 
{ 
    if (compress) 
    { 
     ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
     bitmap.compress(CompressFormat.JPEG, 100, stream); 
     return stream.toByteArray(); 
    } 
    else 
    { 
     int bytes = ImageTools.getByteCount(bitmap); 
     ByteBuffer buffer = ByteBuffer.allocate(bytes); 
     bitmap.copyPixelsToBuffer(buffer); 
     return buffer.array(); 
    } 
} 

public static String getPictureMd5Hash(Bitmap bitmap, boolean compress, BooleanHolder error) 
{ 
    error.set(false); 
    try 
    { 
     return getInternalPictureMd5Hash(bitmap, compress); 
    } 
    catch (OutOfMemoryError e) 
    { 
     error.set(true); 
     return null; 
    } 
} 

private static String getInternalPictureMd5Hash(Bitmap bitmap, boolean compress) throws OutOfMemoryError 
{ 
    if (bitmap == null) 
     return null; 

    byte[] bitmapBytes = convertImageToByteArray(bitmap, compress); 

    String s; 
    try 
    { 
     s = new String(bitmapBytes, "UTF-8"); 
    } 
    catch (UnsupportedEncodingException e) 
    { 
     L.e(Updater.class, e); 
     return null; 
    } 

    MessageDigest m = null; 

    try 
    { 
     m = MessageDigest.getInstance("MD5"); 
    } 
    catch (NoSuchAlgorithmException e) 
    { 
     L.e(Updater.class, e); 
    } 

    m.update(s.getBytes(), 0, s.length()); 
    return calcHash(m); 
} 

private static String calcHash(MessageDigest m) 
{ 
    return new BigInteger(1, m.digest()).toString(16); 
} 

누구가에 대한 개선 제안이 있습니까?

답변

1

왜 해독 된 이미지 데이터 자체의 해시를 얻으려고합니까? 귀하의 목적을 위해, 압축 된 형식 데이터의 해시 괜찮을거야 훨씬 더 적은 데이터를 다룹니다 이후 생산 훨씬 빨리 생산할 수 있습니다 ..

나는 당신이 파일에 이미지 데이터를 캐스팅하는 것 같아요 데이터베이스 캐싱도 잘 작동합니다). 사실

MessageDigest digester = MessageDigest.getInstance("MD5"); 
byte[] bytes = new byte[8192]; 
int byteCount; 
while ((byteCount = in.read(bytes)) > 0) { 
    digester.update(bytes, 0, byteCount); 
} 
byte[] digest = digester.digest(); 
+0

, 나는 Picasso'이 (에서 하나를 두 이미지를 얻을 수'사용 : 그에서 당신이하는 다이제스트 잘 당신을 제공을 생산하는 표준 코드를 가리 킵니다 다시 입력 스트림으로 데이터를 얻을 수 있습니다 서버와 현재 전화 중 하나) ... 그래서 두 이미지는 비트 맵으로 메모리에, 해시를 계산할 때 ...하지만 분할 된 다이제스트 기능은 개선 자체가 될 것입니다, 나는 – prom85

+0

btw, 다이제스트 함수를 분할한다고 생각합니다 정말로 느리게 만들 수 있습니다 ... 1KB 대신 1MB를 사용합니다 ... 내 휴대 전화에서 테스트하면 약 100 배의 속도 차이가 있습니다 (내 이미지는 모두 1MB보다 작지만). 예를 들어 도움이되었다고 생각합니다. 문제가 해결 될 것이므로 테스트 해봐야합니다. – prom85