java - BufferedImage 转换为 Android 位图

标签 java android bitmap

我遇到了问题。我需要将 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/

相关文章:

java - 使用字符串与字节[]作为值,映射中的内存使用情况

java - Hibernate 4.3如何配置二级缓存

android - 将触摸事件委托(delegate)给另一个 View

jQuery 手机 : Page transition effects are barely noticeable

java - Android 中如何将手写笔记转换为文本笔记?

android - 错误 :Failed to find: com. google.guava :guava:18. 0.+

delphi - 在 OpenGL 渲染上下文之上叠加图形

c# - 使用 FFMPEG 对实时位图流进行编码

c - BMP 宽度/高度尺寸超过 255?

java - 在 Android 上使用自适应阈值