Ruslan Fatkhullin
Ruslan Fatkhullin

Reputation: 11

BufferedImage into Android bitmap

I've got a problem. I need to save a java BufferedImage object in an String. Convert this String on the Android application into Bitmap. How can I achieve this? Or maybe you can recommend me the other way to transfer image information in the String format.

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;
}

Upvotes: 0

Views: 861

Answers (1)

John smith
John smith

Reputation: 1805

Base64 encoding and decoding of images using Java 8:

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);
    }
}

hope so will work, enjoy your code:)

Upvotes: 1

Related Questions