Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;

public class Main {
    public static Bitmap createIdenticon(String data) {
        try {
            MessageDigest dig = MessageDigest.getInstance("MD5");
            dig.update(data.getBytes());
            return createIdenticon(dig.digest());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public static Bitmap createIdenticon(byte[] hash) {
        int background = Color.parseColor("#00000000");
        return createIdenticon(hash, background);
    }

    public static Bitmap createIdenticon(byte[] hash, int background) {
        Bitmap identicon = Bitmap.createBitmap(5, 5, Bitmap.Config.ARGB_8888);

        float[] hsv = { Integer.valueOf(hash[3] + 128).floatValue() * 360.0f / 255.0f, 0.8f, 0.8f };
        int foreground = Color.HSVToColor(hsv);

        for (int x = 0; x < 5; x++) {
            //Enforce horizontal symmetry
            int i = x < 3 ? x : 4 - x;
            for (int y = 0; y < 5; y++) {
                int pixelColor;
                //toggle pixels based on bit being on/off
                if ((hash[i] >> y & 1) == 1)
                    pixelColor = foreground;
                else
                    pixelColor = background;
                identicon.setPixel(x, y, pixelColor);
            }
        }

        Bitmap bmpWithBorder = Bitmap.createBitmap(48, 48, identicon.getConfig());
        Canvas canvas = new Canvas(bmpWithBorder);
        canvas.drawColor(background);
        identicon = Bitmap.createScaledBitmap(identicon, 46, 46, false);
        canvas.drawBitmap(identicon, 1, 1, null);

        return bmpWithBorder;
    }
}