我有一个base64编码的图像字符串,我将其转换为byte []和bufferedImage,然后再返回该字符串。我得到的两个字符串是不同的。我得到类似expected:<...1HAwCAAAAC0lEQVR42mP[4/x8AAwAB/2+Bq7Y]AAAAASUVORK5CYII=> but was:<...1HAwCAAAAC0lEQVR42mP[8/x8AAwMCAO+ip1s]AAAAASUVORK5CYII=>
的信息。我不确定是什么原因造成的。任何帮助表示赞赏!
// a 1x1 pixel white png image
String imageString = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=";
byte[] bytes = Base64.decode(imageString);
String newString = toBase64String(toImage(bytes), "png");
Assert.assertEquals(imageString, newString); // not equal
public static BufferedImage toImage(final byte[] bytes) {
BufferedImage image = null;
try {
image = ImageIO.read(new ByteArrayInputStream(bytes));
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
public static String toBase64String(final BufferedImage image, final String formatName) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(image, formatName, baos);
return Base64.encodeBase64String(baos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return "";
}