0

我见过很多关于这个的问题,但都是 C#。它们都不是Java,我找不到合适的库。

图片

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

4

2 回答 2

4

你可以看看这个链接。有一个代码可用于生成您的标识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;
}
于 2016-11-20T00:37:41.657 回答
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);
于 2016-11-30T17:33:28.687 回答