java代码生成图片保存到本地

int width = 250;
		int height = 400;
		String content = "你好";
		File file = new File("E:createImage.jpg");
		Font font = new Font("Serif", Font.BOLD, 10);
		
		BufferedImage bufferedImage = new BufferedImage(
				width, 
				height, 
				BufferedImage.TYPE_INT_RGB
			);
		
		Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
		graphics2D.setBackground(Color.WHITE);
		graphics2D.clearRect(0, 0, width, height);
		graphics2D.setPaint(Color.RED);
		FontRenderContext fontRenderContext = graphics2D.getFontRenderContext();
		Rectangle2D stringBounds = font.getStringBounds(content, fontRenderContext);
		double x = (width - stringBounds.getWidth()) / 2;
		double y = (height - stringBounds.getHeight()) / 2;
		double ascent = -stringBounds.getY();
		double baseY = y + ascent;
		graphics2D.drawString(content, (int)x, (int)baseY);
		
		// 1.将图片写到实体图片里 
		try {
			ImageIO.write(bufferedImage, "jpg", file);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		// 2.将图片写到流里
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		try {
			ImageIO.write(bufferedImage, "jpg", byteArrayOutputStream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

你可能感兴趣的:(java)