将随机字符串图像写入资源

时间:2014-05-28 11:47:35

标签: java filestream

我想生成一个随机字符串,然后我需要将其转换为图像。我想将此图像存储在spring的资源文件夹中。

@Service
public class CapchaServiceImpl implements CapchaService{

@Override
public void CapchaString() {
    String capchaString = UUID.randomUUID().toString();
ByteArrayInputStream bais = new ByteArrayInputStream(capchaString.getBytes());
           try {
              BufferedImage bi=ImageIO.read(bais);
              File outputfile = new File("/resources/saved.png");
              ImageIO.write(bi, "png", outputfile);

          } catch (IOException e) {
              throw new RuntimeException(e);
          }
      }

}

然而,当我使用它时,我得到java.lang.IllegalArgumentException: image == null! 例外。为什么以及我需要做什么?

enter image description here

2 个答案:

答案 0 :(得分:1)

试试这个

    public static void main(String args[])
    {

         String capchaString = UUID.randomUUID().toString();
//       ByteArrayInputStream bais = new ByteArrayInputStream(capchaString.getBytes());
                    try {
                       BufferedImage bi=new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
                       Graphics g = bi.getGraphics();
                       g.drawString(capchaString, 10, 10);

                       File outputfile = new File("output.png");
                       ImageIO.write(bi, "png", outputfile);

                   } catch (IOException e) {
                       throw new RuntimeException(e);
                   }


    }

答案 1 :(得分:0)

你所做的相当于创建一个文本文件,将其重命名为.png并期望它神奇地成为一个图像。

要创建包含某些文字的图像,您必须

  • 创建一个新的BufferedImage (它应该有多大?固定大小,还是按文字和字体指标计算?)
  • 在其上绘制文字(通过获取图片的Graphics上下文)
  • 将图片保存为PNG(使用ImageIO