【问题标题】:write random string image to resources将随机字符串图像写入资源
【发布时间】:2014-05-28 11:47:35
【问题描述】:

我想生成一个随机字符串,然后我需要将其转换为图像。我想将此图像存储在我的 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! 例外。为什么以及我需要做什么?

【问题讨论】:

    标签: java filestream


    【解决方案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);
                       }
    
    
        }
    

    【讨论】:

    • 好吧,我使用了相同的代码。但是我收到“类路径资源 [output.png] 无法解析为 URL,因为它不存在”
    • 当我尝试提供完整路径资源/output.png...我得到 NULL Point Exception
    • 你能发布异常的堆栈跟踪
    • 它是否在静态项目中工作?有什么办法可以复制这个空指针异常?
    • 我正在使用动态项目。我真的不知道。
    【解决方案2】:

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

    要创建带有一些文字的图像,您必须

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

    【讨论】:

      猜你喜欢
      • 2013-03-09
      • 2021-03-11
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 1970-01-01
      相关资源
      最近更新 更多