java绘制带姓的圆

public class ImageGenerator {

	private static final Color[] colors = new Color[] { new Color(129, 198, 132), new Color(149, 117, 204), new Color(255, 187, 68),
			new Color(41, 181, 245), new Color(254, 138, 128), new Color(240, 98, 146) };

	/**
	 * 生成图片 int width = 100; int height = 100;
	 * 
	 * @param name
	 * @param width
	 * @param height
	 * @throws IOException
	 */
	public static InputStream generateImg(char ch) throws IOException {
		return generateImg(ch, 80, 80, 40);
	}

	/**
	 * 
	 * @param ch
	 * @param width
	 * @param height
	 * @throws IOException
	 */
	public static InputStream generateImg(char ch, int width, int height, int fontSize) throws IOException {
		BufferedImage bufferedImage = generateBufferedImage(ch, width, height, fontSize);
		ByteArrayOutputStream bs = new ByteArrayOutputStream();
		ImageIO.write(bufferedImage, "png", bs);
		InputStream is = new ByteArrayInputStream(bs.toByteArray());
		return is;
	}

	/**
	 * 
	 * @param ch
	 * @param width
	 * @param height
	 * @throws IOException
	 */
	public static BufferedImage generateBufferedImage(char ch, int width, int height, int fontSize) throws IOException {
		Font font = new Font("黑体", Font.PLAIN, fontSize);
		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = (Graphics2D) bufferedImage.createGraphics();

		// 增加下面代码使得背景透明
		bufferedImage = g2.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
		g2.dispose();
		g2 = bufferedImage.createGraphics();
		
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		
		// g2.setBackground(getRandomColor());
		// g2.clearRect(0, 0, width, height);
		g2.setFont(font);
		g2.drawOval(0, 0, width, height);
		g2.setPaint(getRandomColor());
		g2.fillOval(0, 0, width, height);
		
		g2.setPaint(Color.white);
		FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
		int w = fm.charWidth(ch);
		int h = fm.getAscent();
		g2.drawString((ch + "").toUpperCase(), (width - w) / 2, h + (height - h) / 2 - (fm.getHeight() - h) / 2);

		g2.dispose();
		return bufferedImage;
	}

	public static Color getRandomColor() {
		Random r = new Random();
		return colors[r.nextInt(colors.length)];
	}

	public static void main(String[] args) {
		File imgFile = new File("D:/1111111111111111.png");
		File imgFile2 = new File("D:/11111111111111cdscsdcsdcsdcsdc11.png");
		try {

			IOUtils.copy(ImageGenerator.generateImg('何'), new FileOutputStream(imgFile));
			ImageIO.write(ImageGenerator.generateBufferedImage('A', 100, 100, 50), "png", imgFile2);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("生成完成");
	}
}

  

posted @ 2017-03-28 11:43  天之涯0204  阅读(303)  评论(0编辑  收藏  举报