如何将S3ObjectInputStream转换为Base64 url​​?

时间:2016-05-11 13:12:36

标签: java amazon-web-services amazon-s3 base64 bufferedimage

我在png中有一个AWS S3 bucket图像文件。我正在尝试使用Java SDK获取此图像。到目前为止,这就是我所做的:

public String encodeBase64URL(BufferedImage imgBuf) throws IOException {
    String base64;

    if (imgBuf == null) {
        base64 = null;
    } else {
        Base64 encoder = new Base64();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        ImageIO.write(imgBuf, "PNG", out);

        byte[] bytes = out.toByteArray();
        base64 = "data:image/png;base64," + encoder.encode(bytes)
                .toString();
    }

    return base64;
}

public String saveImageToS3(BufferedImage imgBuf, String id) throws IOException {
    AmazonS3 s3 = new AmazonS3Client();

    File file = File.createTempFile(id, ".png");
    file.deleteOnExit();

    ImageIO.write(imgBuf, "png", file);

    s3.putObject(new PutObjectRequest(bucketName, id, file));
    file.delete();

    return bucketName;
}

public String downloadImageFromS3(String id) throws IOException {
    AmazonS3 s3 = new AmazonS3Client();

    S3Object obj = s3.getObject(new GetObjectRequest(bucketName, id));
    BufferedImage imgBuf = ImageIO.read(obj.getObjectContent());

    String base64 = encodeBase64URL(imgBuf);
    return base64;
}

saveImageToS3方法完全按预期工作。但是,第二种方法返回data:image/png;base64,[B@428d24fa,而它应该是有效的Base64

我做错了什么?请帮忙。

2 个答案:

答案 0 :(得分:1)

您需要使用toString() ,而不是在生成的byte[]上调用[B@428d24fa,这将导致非常无用的String格式strong>返回的字节:

base64 = "data:image/png;base64," + new String(encoder.encode(bytes), "UTF-8");

答案 1 :(得分:0)

我在使用 Base64 encoder = new Base64(); 时遇到了一些问题 所以我通过不使用编码器解决了这个问题,并且我在任何地方都用 Base64.getEncoder() 替换了“encoder”。

示例:-

if (img == null) {

    base64 = null;

} else {

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    ImageIO.write(img,"PNG",out);

    byte bytes[] = out.toByteArray();

    base64 = new String(Base64.getEncoder().encode(bytes),"UTF-8");
}