下面列出了com.google.zxing.client.j2se.MatrixToImageWriter#toBufferedImage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 生成二维码并响应到浏览器
*
* @param content
* @param response
*/
public static void createQRCode(String content, HttpServletResponse response) {
int width = 300, height = 300;
String format = "png";
Map<EncodeHintType, Object> hashMap = new HashMap<>();
hashMap.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8);
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hashMap.put(EncodeHintType.MARGIN, 1);
try {
response.setHeader("Cache-control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setHeader("content-type", "image/png");
response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
response.setDateHeader("Expires", 0);
BitMatrix bitMatrix = new MultiFormatWriter()
.encode(content, BarcodeFormat.QR_CODE, width, height, hashMap);
BufferedImage img = MatrixToImageWriter.toBufferedImage(bitMatrix);
ImageIO.write(img, format, response.getOutputStream());
} catch (Exception e) {
log.warn("create QRCode error message:{}", e.getMessage());
}
}
public static BufferedImage PDF417(String code, int pdf417ErrorCorrectionLevel,
Compaction pdf417Compact,
int pdf417Width, int pdf417Height, int pdf417Margin) {
try {
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, pdf417ErrorCorrectionLevel);
hints.put(EncodeHintType.MARGIN, pdf417Margin);
if (pdf417Compact == null) {
hints.put(EncodeHintType.PDF417_COMPACT, false);
} else {
hints.put(EncodeHintType.PDF417_COMPACT, true);
hints.put(EncodeHintType.PDF417_COMPACTION, pdf417Compact);
}
BitMatrix bitMatrix = new MultiFormatWriter().encode(code,
BarcodeFormat.PDF_417, pdf417Width, pdf417Height, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
} catch (Exception e) {
logger.error(e.toString());
return null;
}
}
public static BufferedImage DataMatrix(String code,
int dmWidth, int dmHeigh) {
try {
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(code,
BarcodeFormat.DATA_MATRIX, dmWidth, dmHeigh, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
} catch (Exception e) {
logger.error(e.toString());
return null;
}
}
/**
* 生成带有logo的二维码
* @param text 生成文本
* @param logoInputStream logo文件输入流
* @param qrCodeWidth 二维码宽度
* @param qrCodeHeight 二维码高度
* @param logoWidth logo宽度
* @param logoHeight logo高度
* @param ENCODE_HINTS 二维码配置
* @return 输出流
* @throws WriterException
* @throws IOException
*/
private static Thumbnails.Builder<BufferedImage> createWidthLogo(String text, InputStream logoInputStream, int qrCodeWidth, int qrCodeHeight, int logoWidth, int logoHeight,
String format, Map<EncodeHintType, Object> ENCODE_HINTS) throws WriterException, IOException {
BitMatrix bitMatrix = createBitMatrix(text, BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeHeight, ENCODE_HINTS);
/* 生成二维码的bufferedImage */
BufferedImage qrcode = MatrixToImageWriter.toBufferedImage(bitMatrix);
/* 创建图片构件对象 */
Thumbnails.Builder<BufferedImage> builder = Thumbnails.of(new BufferedImage(qrCodeWidth, qrCodeHeight, BufferedImage.TYPE_INT_RGB));
BufferedImage logo = ImageIO.read(logoInputStream);
BufferedImage logoImage = Thumbnails.of(logo).size(logoWidth, logoHeight).asBufferedImage();
/* 设置logo水印位置居中,不透明 */
builder.watermark(Positions.CENTER, qrcode, 1F)
.watermark(Positions.CENTER, logoImage, 1F)
.scale(1F)
.outputFormat(format);
return builder;
}
/**
* 二维码信息写成JPG BufferedImage
*
* @param content
* @param width
* @param height
* @return
*/
public static BufferedImage writeInfoToJpgBuffImg(String content, int width, int height) {
if (width < 250) {
width = 250;
}
if (height < 250) {
height = 250;
}
BufferedImage re = null;
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
BitMatrix bitMatrix = multiFormatWriter.encode(content,
BarcodeFormat.QR_CODE, width, height, hints);
re = MatrixToImageWriter.toBufferedImage(bitMatrix);
} catch (Exception e) {
e.printStackTrace();
}
return re;
}
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/{productId}/ean")
public ResponseEntity<?> getProductEAN(@PathVariable String productId) throws WriterException, IOException {
Product product = repository.findOne(productId);
if (product == null) {
return ResponseEntity.notFound().build();
}
EAN13Writer ean13Writer = new EAN13Writer();
BitMatrix matrix = ean13Writer.encode(product.getEan(), BarcodeFormat.EAN_13, 300, 200);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(matrix);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", baos);
byte[] imageData = baos.toByteArray();
ByteArrayResource byteArrayResource = new ByteArrayResource(imageData);
return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(byteArrayResource);
}
public static byte[] createQRCodeWithDescription(String text, String description) {
try (InputStream fi = new ClassPathResource("/alfio/font/DejaVuSansMono.ttf").getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
BitMatrix matrix = drawQRCode(text);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(matrix);
BufferedImage scaled = new BufferedImage(200, 230, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = (Graphics2D)scaled.getGraphics();
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.drawImage(bufferedImage, 0,0, null);
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 200, 200, 30);
graphics.setColor(Color.BLACK);
graphics.setFont(Font.createFont(Font.TRUETYPE_FONT, fi).deriveFont(14f));
graphics.drawString(center(truncate(description, 23), 25), 0, 215);
ImageIO.write(scaled, "png", baos);
return baos.toByteArray();
} catch (WriterException | IOException | FontFormatException e) {
throw new IllegalStateException(e);
}
}
/**
* 创建二维码
*
* @param content 二维码内容
* @param width 宽度
* @param height 高度
* @param margin 二维码边距
* @return BufferedImage 返回图片
* @throws WriterException 异常
*/
public static BufferedImage createQrCode(String content, int width, int height, int margin) throws WriterException {
Map<EncodeHintType, Comparable> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 字符串编码
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 纠错等级
hints.put(EncodeHintType.MARGIN, margin); // 图片边距
QRCodeWriter writer = new QRCodeWriter();
return MatrixToImageWriter.toBufferedImage(writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints));
}
public static BufferedImage qRCodeCommon(String content, String imgType, int size){
int imgSize = 67 + 12 * (size - 1);
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
try{
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, imgSize, imgSize, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}catch (WriterException e){
e.printStackTrace();
}
return null;
}
public static BufferedImage generateCode128BarcodeImage(String barcodeText) throws Exception {
Code128Writer barcodeWriter = new Code128Writer();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.CODE_128, 300, 150);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
public static BufferedImage generateQRCodeImage(String barcodeText) throws Exception {
QRCodeWriter barcodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.QR_CODE, 200, 200);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
public static BufferedImage QR(String code,
ErrorCorrectionLevel qrErrorCorrectionLevel,
int qrWidth, int qrHeight, int qrMargin, File picFile) {
try {
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, qrErrorCorrectionLevel);
hints.put(EncodeHintType.MARGIN, qrMargin);
QRCodeWriter writer = new QRCodeWriter();
BitMatrix bitMatrix = writer.encode(code,
BarcodeFormat.QR_CODE, qrWidth, qrHeight, hints);
BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
if (picFile != null) {
BufferedImage pic = ImageFileReaders.readImage(picFile);
if (pic != null) {
double ratio = 2;
switch (qrErrorCorrectionLevel) {
case L:
ratio = 0.16;
break;
case M:
ratio = 0.20;
break;
case Q:
ratio = 0.25;
break;
case H:
ratio = 0.30;
break;
}
// https://www.cnblogs.com/tuyile006/p/3416008.html
// ratio = Math.min(2 / 7d, ratio);
int width = (int) ((qrImage.getWidth() - writer.leftPadding * 2) * ratio);
int height = (int) ((qrImage.getHeight() - writer.topPadding * 2) * ratio);
return BarcodeTools.centerPicture(qrImage, pic, width, height);
}
}
return qrImage;
} catch (Exception e) {
logger.error(e.toString());
return null;
}
}
public static BufferedImage generatePDF417BarcodeImage(String barcodeText) throws Exception {
PDF417Writer barcodeWriter = new PDF417Writer();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.PDF_417, 700, 700);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
public static BufferedImage createQRImage(String inviteUrl) throws WriterException {
BitMatrix bitMatrix = getBitMatrix(inviteUrl);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
public static BufferedImage generateUPCABarcodeImage(String barcodeText) throws Exception {
UPCAWriter barcodeWriter = new UPCAWriter();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.UPC_A, 300, 150);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
public static BufferedImage generateEAN13BarcodeImage(String barcodeText) throws Exception {
EAN13Writer barcodeWriter = new EAN13Writer();
BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.EAN_13, 300, 150);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
/**
* 返回一个 BufferedImage 对象
*
* @param content 二维码内容
* @param width 宽
* @param height 高
*/
public static BufferedImage toBufferedImage(String content, int width, int height) throws WriterException, IOException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
/**
* CODE_128
*
* @param content
* @return
*/
public static BufferedImage createBarCode(String content) {
BitMatrix bitMatrix = createBarCode(content, BarcodeFormat.CODE_128, 320);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
/**
* 返回一个 BufferedImage 对象
*
* @param content 二维码内容
*/
public static BufferedImage toBufferedImage(String content) throws WriterException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
/**
* 返回一个 BufferedImage 对象
*
* @param content 二维码内容
* @param width 宽
* @param height 高
*/
public static BufferedImage toBufferedImage(String content, int width, int height)
throws WriterException {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, HINTS);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}