0

I converted BufferedImageto Base64 format.

How do I now convert this Base64 string to Image again?

I always get an error: image == null

try {
    BufferedImage bimg;
    Robot bot;
    bot = new Robot();
    bimg = bot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
    ImageIO.write(bimg, "PNG", new File("C:\\Users\\****\\Desktop\\client.png"));
    /// encode
    String imageString;
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        ImageIO.write(bimg, "PNG", bos);
        byte[] imageBytes = bos.toByteArray();
        imageString = Base64.getEncoder().encodeToString(imageBytes);
    }
    System.out.println("Base64 -" + imageString);
    /// decode
    String decoded = new String(Base64.getDecoder().decode(imageString));
    // System.out.println(decoded);
    byte[] imageByte2 = decoded.getBytes();
    ImageIO.write(ImageIO.read(new ByteArrayInputStream(imageByte2)), "PNG", new File("C:\\Users\\***\\Desktop\\decoded.png"));
} catch (AWTException | HeadlessException | IOException e) {
    JOptionPane.showMessageDialog(null, e);
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Br.GH
  • 27
  • 1
  • 8
  • Why are you creating a new string in your `///decode` step? That is completely unnecessary (and wrong). `decode(imageString)` already returns your `byte[]`. – Sotirios Delimanolis Dec 28 '16 at 18:37
  • sorry I didn't understand, I want send this string through socket and start ///decode step at receiver. – Br.GH Dec 28 '16 at 18:41
  • So you have `imageString`, that's your Base64 string. You'll have that string on both your sending and receiving sides. It makes no sense to Base64 decode that into the binary data and try to create a `String` from it. The `Base64.getDecoder().decode(imageString)` call already gives you the `byte[]` content of your image. Assign **that** to `imageByte2`. – Sotirios Delimanolis Dec 28 '16 at 18:44
  • Thank you it's working now. I just removed decoded string and I add Base64.getDecoder().decode(imageString) to imageBytes2 . – Br.GH Dec 28 '16 at 19:00

0 Answers0