日期:2014-05-20 浏览次数:20964 次
public class Test { private static final int WIDTH = 200; private static final int HEIGHT = 300; private static final String OUT_PATH = "image.jpg"; public static void main(String[]args) { BufferedImage buffImg = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT); g.setColor(Color.BLACK); g.fillOval(0, 0, 30, 30); g.fillOval(100, 100, 30, 30); g.drawLine(15, 15, 115, 115); g.dispose(); ImageIcon icon = new ImageIcon(buffImg); File f = new File(OUT_PATH); OutputStream out; try { out = new FileOutputStream(f); ImageIO.write(buffImg, "jpg", out); out.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
------解决方案--------------------
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bi.createGraphics(); Ellipse2D.Double circle = new Ellipse2D.Double(x,y,w,h); g2d.setPaint(Color.BLUE); g2d.fill(circle); Line2D.Double line = new Line2D.Double(x1,y1,x2,y2); g2d.draw(line); ... // draw/fill other shapes g2.dispose(); ImageIO.write(bi,"PNG",new File(...)); // write to file
------解决方案--------------------
还应该使用 setRenderingHint(RenderingHints.Key hintKey, Object hintValue) 设置一下抗锯齿。