文本文件到图像转换

时间:2012-11-08 08:57:44

标签: java image javax.imageio

我有一个字符串,我将其转换为bytes []然后我将其编码为带回图像但问题是它没有将其创建回图像

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

我收到此错误,但我在控制台上收到此消息

     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)

1 个答案:

答案 0 :(得分:3)

这会对你有帮助。

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

或者,如果您希望导出到png,那么您可以拥有支持透明度的图像。

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);