如何使用Java或Android创建identicons?

时间:2016-11-19 19:31:53

标签: java android identicon

我已经看到很多关于此的问题,但所有这些都是C#。它们都不是Java,我无法为此找到合适的库。

image

什么库可以通过给它一个字符串/哈希以编程方式为我做这个?该算法实际上是在StackExchange上实现的。

2 个答案:

答案 0 :(得分:1)

您可以查看此链接。您可以使用一段代码生成您的识别符http://www.davidhampgonsalves.com/Identicons

Java的代码如下:

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;
}

答案 1 :(得分:1)

我解决了这个问题。

我使用了Gravatar。我首先获得了图像的链接,并将其存储为String,如下所示:

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

然后,我使用了Glide:

Glide.with(ProfilePictureChooserActivity.this)
      .load(identiconURL)
      .centerCrop()
      .into(imageView);