How can I create identicons using Java or Android?

1.2k views Asked by At

I've seen many questions about this, but all of them are C#. None of them are Java, and I couldn't find a proper library for this.

image

What library can do this for me programmatically by giving it a string/hash? This algorithm is actually implemented on StackExchange.

2

There are 2 answers

0
Ali Bdeir On BEST ANSWER

I solved the problem.

I used Gravatar. I first got the link of the image and stored it as a String like this:

String identiconURL = "http://www.gravatar.com/avatar/" + userID + "?s=55&d=identicon&r=PG";

Then, I used Glide:

Glide.with(ProfilePictureChooserActivity.this)
      .load(identiconURL)
      .centerCrop()
      .into(imageView);
2
Kevin G. On

You can look at this link. There is a code that you could use to generate your identicons http://www.davidhampgonsalves.com/Identicons

The code for Java is the following one:

public static BufferedImage generateIdenticons(String text, int image_width, int image_height){
        int width = 5, height = 5;

        byte[] hash = text.getBytes();

        BufferedImage identicon = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        WritableRaster raster = identicon.getRaster();

        int [] background = new int [] {255,255,255, 0};
        int [] foreground = new int [] {hash[0] & 255, hash[1] & 255, hash[2] & 255, 255};

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

        BufferedImage finalImage = new BufferedImage(image_width, image_height, BufferedImage.TYPE_INT_ARGB);

        //Scale image to the size you want
        AffineTransform at = new AffineTransform();
        at.scale(image_width / width, image_height / height);
        AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
        finalImage = op.filter(identicon, finalImage);

        return finalImage;
}