我遇到了问题。我需要将 java BufferedImage 对象保存在 String 中。将 Android
应用程序上的String
转换为Bitmap
。我怎样才能实现这个目标?或者您可以向我推荐另一种以 String
格式传输图像信息的方法。
public static String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
imageString = Base64.getEncoder().encodeToString(imageBytes);
bos.close();
} catch (IOException e) {
log.error("Can't encode to String");
}
return imageString;
}
最佳答案
使用Java 8对图像进行Base64编码和解码:
public static String imgToBase64String(final RenderedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
public static BufferedImage base64StringToImg(final String base64String) {
try {
return ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(base64String)));
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
希望这样能行得通, 享受你的代码:)
关于java - BufferedImage 转换为 Android 位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32737295/