生成二维码和条形码
依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
代码
package com.zyj.common.utils;
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.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.font.FontDesignMetrics;
import javax.imageio.ImageIO;
import javax.print.*;
import javax.print.attribute.HashPrintJobAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSize;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
import java.util.HashMap;
import static com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage;
public class CreateCodeUtils {
private static int qrHeight=520;
private static int qrWidth=520;
private static int numberWidth=400;
private static int numberHeight=30;
private static int digitSpace=21;
public static String generateBarcode(String content){
BufferedImage barcodeImage =generateBarcodeImage(content);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(barcodeImage, "png", baos);
} catch (IOException e) {
throw new RuntimeException(e);
}
byte[] imageBytes = baos.toByteArray();
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
return base64Image;
}
public static BufferedImage generateBarcodeImage(String content){
int width=300;
int height=100;
BitMatrix bitMatrix = null;
try {
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, width, height);
} catch (WriterException e) {
throw new RuntimeException(e);
}
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for(int x=0;x<width;x++){
for(int y=0;y<height;y++){
bufferedImage.setRGB(x,y,bitMatrix.get(x,y)?0xFF000000:0xFFFFFFFF);
}
}
return bufferedImage;
}
public static String generateQRCodeBase64(String text,int width,int height){
HashMap<EncodeHintType, Object> hits = new HashMap<>();
hits.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
hits.put(EncodeHintType.ERROR_CORRECTION.MARGIN,1);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix =null;
try {
bitMatrix=qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height,hits);
} catch (WriterException e) {
throw new RuntimeException(e);
}
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for(int x=0;x<width;x++){
for(int y=0;y<height;y++){
image.setRGB(x,y,bitMatrix.get(x,y)?0xFF000000:0xFFFFFFFF);
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(image,"png",baos);
} catch (IOException e) {
throw new RuntimeException(e);
}
byte[] imageBytes = baos.toByteArray();
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
return base64Image;
}
public static BufferedImage generateCodeQRToBuffImage(String text,String number){
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
BitMatrix bitMatrix = null;
try {
bitMatrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, qrWidth, qrHeight);
} catch (WriterException e) {
throw new RuntimeException(e);
}
BufferedImage qrImage = toBufferedImage(bitMatrix);
addFontImage(qrImage,number);
return qrImage;
}
private static void addFontImage(BufferedImage source, String number) {
int defineWidth = numberWidth;
int defineHeight = numberHeight;
BufferedImage textImage = new BufferedImage(defineWidth, defineHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) textImage.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setBackground(Color.WHITE);
g2.clearRect(0, 0, defineWidth, defineHeight);
g2.setPaint(Color.BLACK);
FontRenderContext context = g2.getFontRenderContext();
Font font = new Font("Arial", Font.BOLD, 30);
g2.setFont(font);
LineMetrics lineMetrics = font.getLineMetrics(number, context);
FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);
float offset=0;
float y = (defineHeight + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;
for(int i=0;i<number.length();i++){
char digit=number.charAt(i);
g2.drawString(String.valueOf(digit),(int)offset,(int)y);
offset+=digitSpace;
}
Graphics2D graph = source.createGraphics();
graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
int width = textImage.getWidth(null);
int height = textImage.getHeight(null);
graph.drawImage(textImage, (qrWidth-width)/8*5, qrHeight-height*2, width, height, Color.WHITE, null);
graph.dispose();
}
private static BufferedImage myToBufferedImage(BitMatrix bitMatrix) {
int width=bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
for(int x=0;x<width;x++){
for(int y=0;y<height;y++){
image.setRGB(x,y,bitMatrix.get(x,y)?Color.BLACK.getRGB():Color.WHITE.getRGB());
}
}
return image;
}
public static void printImage(BufferedImage image) throws PrintException, IOException {
PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob printJob = defaultPrintService.createPrintJob();
DocFlavor.INPUT_STREAM flavor = DocFlavor.INPUT_STREAM.PNG;
SimpleDoc doc = new SimpleDoc(imageToInputStream(image), flavor, null);
HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
MediaSize mediaSize = MediaSize.ISO.A7;
attributes.add(mediaSize.getMediaSizeName());
printJob.print(doc,attributes);
}
public static InputStream imageToInputStream(BufferedImage image) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image,"png",os);
return new ByteArrayInputStream(os.toByteArray());
}
public static void saveImageToFile(BufferedImage image,String outputName) throws IOException {
File outputFile = new File(outputName);
ImageIO.write(image,"png",outputFile);
}
}