直接上代码:最后有main方法可以测试
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.google.zxing.common.BitMatrix;
@Component
public class CodeUtil {
private static String LOGO_PATH;
@Value("${conference.logoPath}")
public void setLogoPath(String logoPath) {
LOGO_PATH = logoPath;
}
/**
*二维码实现
* @param msg
* @param path
*/
public static void createBarCode(String msg, String path, String fullPathName){
try {
File filePath = new File(path);
if(!filePath.exists()) {
filePath.mkdirs();
}
int width = 300;
int height = 300;
BitMatrix matrix = MatrixToImageWriterEx.createQRCode(msg, width, height);
int margin = 5; //自定义白边边框宽度
matrix = updateBit(matrix, margin); //生成新的bitMatrix
MatrixToLogoImageConfig logoConfig = new MatrixToLogoImageConfig(Color.BLUE, 4);
MatrixToImageWriterEx.writeToFile(matrix, "jpg", fullPathName, LOGO_PATH, logoConfig);
// MatrixToImageWriterEx.writeToFile(matrix, "jpg", fullPathName, "F:\\temp\\logo.png", logoConfig);
BufferedImage bi = ImageIO.read(new File(fullPathName)); ;
bi = zoomInImage(bi,width,height);//根据size放大、缩小生成的二维码
File target = new File(fullPathName);
ImageIO.write(bi, "jpg", target); //生成二维码图片
}catch (Exception e) {
e.printStackTrace();
}
}
private static BitMatrix updateBit(BitMatrix matrix, int margin){
int tempM = margin*2;
int[] rec = matrix.getEnclosingRectangle(); //获取二维码图案的属性
int resWidth = rec[2] + tempM;
int resHeight = rec[3] + tempM;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); // 按照自定义边框生成新的BitMatrix
resMatrix.clear();
for(int i= margin; i < resWidth- margin; i++){ //循环,将二维码图案绘制到新的bitMatrix中
for(int j=margin; j < resHeight-margin; j++){
if(matrix.get(i-margin + rec[0], j-margin + rec[1])){
resMatrix.set(i,j);
}
}
}
return resMatrix;
}
/**
* 图片放大缩小
*/
public static BufferedImage zoomInImage(BufferedImage originalImage, int width, int height){
BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
Graphics g = newImage.getGraphics();
g.drawImage(originalImage, 0,0,width,height,null);
g.dispose();
return newImage;
}
public static void main(String[] args) {
String msg = "http://www.baidu.com";
String path = "E:\\temp\\codePath1\\";
CodeUtil.createBarCode(msg, path, path + "1.png");
}
}