<!---首先需要用到BufferedImage在内存中构建一张图片-----> BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); <!-----最后一个参数表示一个图像,它具有合成整数像素的 8 位 RGB 颜色分量-----> <!---往图片上写需要用到Graphics,相当于一个画笔-----> Graphics g = img.getGraphics(); <!---------------新建这4个方法来画----------------------> setBacoground(g); /*画背景图*/ setBorder(g);/*画边框*/ setInterferingline(g); /*画干扰线*/ setWord((Graphics2D)g); /*写字,字体旋转需要用到Graphics2D中的rotate方法*/ <!-----------告诉浏览器以图片形式打开,将图片写给浏览器-------------> response.setContentType("image/jpeg"); ImageIO.write(img, "jpg", response.getOutputStream()); <!-----------下面是4个方法的代码-------------> private void setBacoground(Graphics g) { g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT); } private void setBorder(Graphics g) { g.setColor(Color.black); g.drawRect(1, 1, WIDTH-2, HEIGHT-2); } private void setInterferingline(Graphics g) { g.setColor(Color.red); for(int i=0; i<4; i++) { int x1 = new Random().nextInt(WIDTH); int y1 = new Random().nextInt(HEIGHT); int x2 = new Random().nextInt(WIDTH); int y2 = new Random().nextInt(HEIGHT); g.drawLine(x1, y1, x2, y2); } } private void setWord(Graphics2D g) { g.setColor(Color.BLACK); g.setFont(new Font("黑体", Font.BOLD, 20)); String bute = "这里是常用字的正则表达式,太多就不贴了"; int x = 5; for(int i=0; i<4; i++) { int degree = new Random().nextInt() % 30; String ch = bute.charAt(new Random().nextInt(bute.length()))+""; g.rotate(degree*Math.PI/180,x,20); g.drawString(ch,x,20); g.rotate(-degree*Math.PI/180,x,25); x += 30; } }