import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
*
* @author: xiaogang
* @date: 2018/8/1 0:27
* To change this template use File | Settings | File Templates.
* Description:
*/
public class GenerateQrCodeUtil {
/**
* 背景色
*/
private static final int WHITE = 0xFFFFFFFF;
/**
* 前景色
*/
private static final int BLACK = 0xFF000000;
/**
* 二维码宽度
*/
private static int width = 168;
/**
* 二维码高度
*/
private static int height = 168;
/**
* logo图片所在的classpath下的路径,如果该路径下没有图片,则不会再二维码中添加logo图
*/
private static String logoPath = "/static/logo.png";
/**
* 将指定信息生成图片对象
* @param content 二维码里面的信息
* @return
* @throws WriterException
* @throws IOException
*/
public static BufferedImage drawQrCode(String content) throws WriterException, IOException {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
BarcodeFormat format = BarcodeFormat.QR_CODE;
Map<EncodeHintType, Object> hints = new HashMap<>();
EncodeHintType key = EncodeHintType.CHARACTER_SET;
hints.put(key,"utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN,1);
BitMatrix bitMatrix = multiFormatWriter.encode(content, format, width, height, hints);
BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
for (int i = 0; i < width; i++) {
for (int y = 0; y < height; y++) {
bufferedImage.setRGB(i,y,bitMatrix.get(i,y) ? BLACK : WHITE);
}
}
if (logoPath != null) {
InputStream resourceAsStream = GenerateQrCodeUtil.class.getResourceAsStream(logoPath);
if (resourceAsStream != null && resourceAsStream.available() > 1) {
BufferedImage logoImg = ImageIO.read(resourceAsStream);
int logoWidth = 40;
int logoHeight = 40;
int x = (width - logoWidth) / 2;
int y = (height - logoHeight) / 2;
graphics.drawImage(logoImg,x,y,logoWidth,logoHeight,null);
}else {
System.out.println("指定路径下没有找到logo图片");
}
}
return bufferedImage;
}
/**
* 将指定信息生成二维码图片文件
* @param content 二维码里面的信息
* @param filePath 文件路径和文件名
* @return
* @throws IOException
* @throws WriterException
*/
public static Boolean generateQrCodeImage(String content,String filePath) throws IOException, WriterException {
BufferedImage bufferedImage = drawQrCode(content);
boolean write = ImageIO.write(bufferedImage, "png", new File(filePath));
return write;
}
private GenerateQrCodeUtil(){}
}
java 生成二维码图片
猜你喜欢
转载自blog.csdn.net/u013958151/article/details/81323308
今日推荐
周排行