将 Gravatar 图片保存到数据库

Saving Gravatar images to the database

我想使用 Gravatar but I don't want to publish users MD5 hashes of their e-mail addresses. And there is more potential problems。所以我决定下载它们并将它们存储在我的数据库中。
但是我的个人资料图片 (Earlybird) 在下载后看起来很糟糕:

这是我使用的代码。

try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
    final URL url = new URL("http://www.gravatar.com/avatar/" + account.getGravatarHash() + "?d=identicon");
    final BufferedImage image = ImageIO.read(url);
    ImageIO.write(image, "jpg", baos);
    pic = baos.toByteArray();
} catch (IOException e) {
    e.printStackTrace();
}

pic 中的值然后直接存储到数据库中。我数据库中的其他图片存储良好,所以问题一定出在这些行中。

编辑:
我只是通过将 "jpg" 更改为 "png" 来部分解决问题,甚至认为 Gravatar tutorial 提到了 "jpg"。我也不想指定图像格式(除非所有 Gravatars 都是 png)。我可以避免吗?我只想保存我得到的字节。

浏览器在大多数情况下使用原始字节。但是,非常感谢为每张图片发送 "Content-Type: image/..." header。

当您在数据库中保存字节时,您还必须

  1. 要么保存图片 内容类型,由 Gravatar 为此图片提供,要么
  2. 将图像转换为您的默认格式,这样您就可以对数据库中所有图像的内容类型进行硬编码

要获得Gravatar提供的header秒,您可以使用Apache HTTP Client

要将图像转换为您喜欢的格式,您可以使用 ImageIO。

我找到了一个 similar problem 的有效解决方案:

try (ByteArrayOutputStream baos = new ByteArrayOutputStream()){
    final URL url = new URL("http://www.gravatar.com/avatar/" + account.getGravatarHash() + "?d=identicon");
    InputStream inputStream = url.openStream();
    byte[] buffer = new byte[1024];
    int n;
    while (-1 != (n = inputStream.read(buffer))) {
        baos.write(buffer, 0, n);
    }
    inputStream.close();
    pic = baos.toByteArray();
} catch (IOException e) {
    e.printStackTrace();
}

看起来这适用于 pngjpg Gravatars。