Java‎ > ‎

MD5 Hash of an Image

Creating an MD5 Hash of an image in Java is fairly simple, and below I have included the code to do this.

First, you must read the image into a ByteArray Output Stream, then digest the ByteArray into an MD5 Hash, finally, you may want to convert this ByteArray into a HexString.

package md5hashexample;

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

 * @author Matthew Jones (Matt Jones)
 * Created for a Java Example on
public class Main {

    public static void main(String[] args) throws NoSuchAlgorithmException, Exception {

        File input = new File("C:/image.png");
        BufferedImage buffImg =;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(buffImg, "png", outputStream);
        byte[] data = outputStream.toByteArray();

        System.out.println("Start MD5 Digest");
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hash = md.digest();
    }                                       // Belongs to main class
    // Below method of converting Byte Array to hex
    // Can be found at:
    static String returnHex(byte[] inBytes) throws Exception {
        String hexString = null;
        for (int i=0; i < inBytes.length; i++) { //for loop ID:1
            hexString +=
            Integer.toString( ( inBytes[i] & 0xff ) + 0x100, 16).substring( 1 );
        }                                   // Belongs to for loop ID:1
    return hexString;
  }                                         // Belongs to returnHex class

}                                           // Belongs to Main class