不说什么,代码能为我解释。透明的背景重要的一点就是只能在于png格式,而不是jpg格式。
package com.shengdai.gzb.yzmcode.web;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.stereotype.Controller;
import com.shengdai.base.support.struts.BaseStrutsAction;
@Controller
public class YzmCodeAction extends BaseStrutsAction{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int WIDTH=120;
private static final int HEIGHT = 30;
public YzmCodeAction() {
super();
}
@Action
public void validate() {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
//1.设置背景颜色
setBackground(g);
//2.设置边框
setBorder(g);
//3.画干扰线
drawRandomLine(g);
//4.生成随机数
String codes = drawRandomNum((Graphics2D)g);
request.getSession().invalidate();
request.getSession().setAttribute("codes", codes);
//5.将图像写给浏览器
response.setContentType("image/jpeg");
//设置浏览器清除缓存
response.setDateHeader("expries", -1);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
try {
ImageIO.write(image, "png", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
private String drawRandomNum(Graphics2D g) {
g.setColor(Color.BLACK);
g.setFont(new Font("楷体",Font.BOLD,25));
String base = "1234567890qwertyuiopasdfghjklzxcvbnyQWERTYUIOPASDFGHJKLZXCVBNM";
StringBuffer buffer = new StringBuffer();
int x = 5;
for(int i=0;i<4;i++){
int degree = new Random().nextInt()%30;
String ch = base.charAt(new Random().nextInt(base.length())) + "";
buffer.append(ch);
g.rotate(degree*Math.PI/180,x, 30);
g.drawString(ch, x, 25);
//必须要有
g.rotate(-degree*Math.PI/180, x, 30);
x+=30;
}
return buffer.toString().toLowerCase();
}
private void drawRandomLine(Graphics g) {
g.setColor(Color.GRAY);
for(int i=0;i<0;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 setBorder(Graphics g) {
// g.setColor(Color.BLACK);
g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
}
private void setBackground(Graphics2D g) {
//设置背景颜色
// g.setColor(Color.WHITE);
g.setColor(new Color(255, 255, 255, 0));
g.fillRect(0, 0, WIDTH, HEIGHT);
// g.getDeviceConfiguration().createCompatibleImage(WIDTH, HEIGHT, Transparency.TRANSLUCENT);
// g.dispose();
}
}