java字符串转图片示例

179 阅读1分钟

	private static final String str = "美国单日新增确诊逾2.1万例";
	
	public static void main(String[] args) throws Exception 
	{
		createImage(str, new Font("宋体", Font.BOLD, 30), new File( "D://test.png"), 1920, 1080); 
	} 
		  
	public static void createImage(String str, Font font, File outFile, Integer width, Integer height) throws Exception
	{
	    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); 
	    Graphics g = image.getGraphics(); 
	    g.setClip(0, 0, width, height); 
	    g.setColor(Color.white); 
	    g.fillRect(0, 0, width, height);
	    g.setColor(Color.black);
	    g.setFont(font);
	    int x = 60;
	    int y = 50;
	    String[] arr = str.split("\\r\\n");
	    for (String s : arr)
	    {
	    	g.drawString(s, x, y); 
	    	y += 30; 
	    }
	    g.dispose();
	    
	    
	    ImageIO.write(image, "png", outFile);
	}