步骤:
1.导入google 的zxing.jar包
2.核心方法
//生成二维码的类库
private static MultiFormatWriter mutiWriter = new MultiFormatWriter();
/**
* @Description: 生成一个彩色二维码
* @param content 二维码内容
* @param width 宽度
* @param height 高度
* @param path 二维码生成路径
* @author
* @date 2017年11月8日
*/
public static String encode(String content, int width, int height,String path) {
try {
String fileName = UUID.randomUUID()+".png";
File file = new File(path+"/"+fileName);
ImageIO.write(genBarcode(content, width, height),"png", file);
return fileName;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @Description:生成一个二维码
* @param content 内容
* @param width 宽
* @param height 高
* @return
* @throws WriterException
* @throws IOException
* @author
* @date 2017年12月25日
*/
private static BufferedImage genBarcode(String content, int width, int height) throws WriterException, IOException {
Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();
hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 生成二维码
BitMatrix matrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE,width, height, hint);
int w = matrix.getWidth();
int h = matrix.getHeight();
int[] data = new int[w * h];
boolean flag1=true;
int stopx=0;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
if(matrix.get(x, y)){
if(flag1){
flag1=false;
}
}else{
if(flag1==false){
stopx =x;
break;
}
}
}
if(flag1==false)
break;
}
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
if(matrix.get(x, y)){
if((x<stopx)&&(y<stopx)){
Color color = new Color(231, 144, 56);
int colorInt = color.getRGB();
data[y * width + x] =colorInt;
}else{
int num1 = (int) (50 - (50.0 - 13.0)/ matrix.getHeight()* (y + 1));
int num2 = (int) (165 - (165.0 - 72.0) / matrix.getHeight()* (y + 1));
int num3 = (int) (162 - (162.0 - 107.0)/ matrix.getHeight() * (y + 1));
Color color = new Color(num1, num2, num3);
int colorInt = color.getRGB();
data[y * w + x] = colorInt;
}
}else{
data[y * w + x] = -1;//白色
}
}
}
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
image.getRaster().setDataElements(0, 0, width, height, data);
return image;
}
效果图