我想生成一个随机字符串,然后我需要将其转换为图像。我想将此图像存储在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!
例外。为什么以及我需要做什么?
答案 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并期望它神奇地成为一个图像。
要创建包含某些文字的图像,您必须
Graphics
上下文)ImageIO
)