Issue
I have a png
image file in an AWS S3 bucket
. I'm trying to get this image using Java SDK. So far, here is what I have done:
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;
}
The saveImageToS3
method works exactly as expected. However, the second method returns data:image/png;base64,[B@428d24fa
while it should have been a valid Base64
.
What am I doing wrong? Please help.
Solution
Instead of calling toString()
on the resulting byte[]
which will result in the very unhelpful [B@428d24fa
format, you need to create a new String
using the returned bytes:
base64 = "data:image/png;base64," + new String(encoder.encode(bytes), "UTF-8");
Answered By - Kayaman
Answer Checked By - Katrina (JavaFixing Volunteer)