0

I have a string, which i am converting it into bytes[] and then i code it to bring back to image but the problem is that it is not creating it back to the image

              BufferedReader reader2 = new BufferedReader(new FileReader("e:\\imageinString.txt"));
    String buffer, lined = "";

    while ((buffer = reader2.readLine()) != null) {
        lined = lined + buffer;
    }

    byte[] byteArray = lined.getBytes("UTF-16");

    InputStream in = new ByteArrayInputStream(byteArray);
    BufferedImage bImageFromConvert = ImageIO.read(in);

    ImageIO.write(bImageFromConvert, "bmp", new File("e:\\ppp.bmp"));
    reader2.close();

I am getting this error but I am getting this on console

     Exception in thread "main" java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
at javax.imageio.ImageIO.getWriter(ImageIO.java:1591)
at javax.imageio.ImageIO.write(ImageIO.java:1520)
at imagereading.Imagereading.main(Imagereading.java:47)
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Xara
  • 8,748
  • 16
  • 52
  • 82
  • 2
    1) You cannot expect to write `String` bytes into an image! You need to create a `BufferedImage`, get a `Graphics` object from the image, write the text to that, then save the image. 2) Why, *why,* ***why*** on earth do people want to turn perfectly good text into an image? – Andrew Thompson Nov 08 '12 at 09:00
  • Even if you convert String to byte, the byte contents are still String and not Image. It only change its form. – Mawia Nov 08 '12 at 09:13

1 Answers1

3

This will help you.

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2 = image.createGraphics();
g2.drawString(s, x, y);
...
g2.dispose();
ImageIO.write(image, "jpg", file);

Or if you prefer to export to png then you can have an image that supports transparency.

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
Dan D.
  • 32,246
  • 5
  • 63
  • 79
  • I think PNG would be better for textual images. See [this example](http://stackoverflow.com/questions/5995798/java-text-on-image/5998015#5998015) for comparisons. – Andrew Thompson Nov 08 '12 at 11:29
  • @Dan Please help me out, I am not able to understand where I have to pass the string which I have got from a text file in order to convert that string into an image – Xara Nov 08 '12 at 18:33
  • The string must be passed as the first parameter of the drawString method. – Dan D. Nov 09 '12 at 12:24