java中Zxing和Barcode4J生成条形码和二维码

依赖的工具包:

  	
	
	    com.google.zxing
	    core
	    3.3.3
	
  	
	
	    com.google.zxing
	    javase
	    3.3.3
	
	
	
	    net.sf.barcode4j
	    barcode4j
	    2.1
	  	
	
	
	    org.apache.avalon.framework
	    avalon-framework-api
	    4.3.1
	

 

1、Zxing生成和解析条形码

package zxing;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

public class BarCodeTest {
	/**
	 * generateCode 根据code生成相应的一维码
	 * @param file 一维码目标文件
	 * @param code 一维码内容
	 * @param width 图片宽度
	 * @param height 图片高度
	 */
    public static void generateCode(File file, String code, int width, int height) {
    	//定义位图矩阵BitMatrix
        BitMatrix matrix = null;

        try {
            // 使用code_128格式进行编码生成100*25的条形码
        	MultiFormatWriter writer = new MultiFormatWriter();
        	
            matrix = writer.encode(code,BarcodeFormat.CODE_128, width, height, null);
            //matrix = writer.encode(code,BarcodeFormat.EAN_13, width, height, null);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        
        //将位图矩阵BitMatrix保存为图片
        try (FileOutputStream outStream = new FileOutputStream(file)) {
            ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "png",
                    outStream);
            outStream.flush();
        } catch (Exception e) {
        	e.printStackTrace();
        }
    }
    
    /**
     * readCode 读取一张一维码图片
     * @param file 一维码图片名字
     */
    public static void readCode(File file){
        try {
        	BufferedImage image = ImageIO.read(file);
            if (image == null) {
                return;
            }
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            
            Map hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "GBK");
            hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            
            Result result = new MultiFormatReader().decode(bitmap, hints);
            System.out.println("条形码内容: "+result.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        //generateCode(new File("1dcode.png"), "123456789012", 500, 250);
    	readCode(new File("1dcode.png"));
    }
}

2、Zxing生成和解析二维码

package zxing;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class QRCodeTest {
    /*
     * 定义二维码的宽高
     */
    private static int WIDTH = 300;
    private static int HEIGHT = 300;
    private static String FORMAT = "png";//二维码格式

    //生成二维码
    public static void generateQRCode(File file, String content) {
        //定义二维码参数
        Map hints = new HashMap<>();

        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置编码
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//设置容错等级
        hints.put(EncodeHintType.MARGIN, 2);//设置边距默认是5

        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            Path path = file.toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);//写到指定路径下

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //读取二维码
    public static void readQrCode(File file) {
        MultiFormatReader reader = new MultiFormatReader();
        try {
            BufferedImage image = ImageIO.read(file);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            Map hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "utf-8");//设置编码
            Result result = reader.decode(binaryBitmap, hints);
            System.out.println("解析结果:" + result.toString());
            System.out.println("二维码格式:" + result.getBarcodeFormat());
            System.out.println("二维码文本内容:" + result.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        generateQRCode(new File("2dcode.png"), "https://www.baidu.com");
    	readQrCode(new File("2dcode.png"));
    	//readQrCode(new File("2dcode.jpg"));
    }
}

 3、Barcode4J工具包只能生成,不能解析

生成条形码:

package barcode4j;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

import org.krysalis.barcode4j.impl.code39.Code39Bean;
import org.krysalis.barcode4j.impl.upcean.EAN13Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;


public class BarCodeTest {

	public static void main(String[] args) {
		String msg = "123456789012";
		String path = "1dcode.png";
		generateFile(msg, path);
	}

	public static void generateFile(String msg, String path) {
		File file = new File(path);
		try {
			Code39Bean bean = new Code39Bean();
			//EAN13Bean bean = new EAN13Bean();

			// dpi精度
			final int dpi = 150;
			// module宽度
			//bean.setModuleWidth(0.2);
			final double width = UnitConv.in2mm(2.0f / dpi);
			bean.setWideFactor(3);
			bean.setModuleWidth(width);
			bean.doQuietZone(false);

			String format = "image/png";
			// 输出到流
			BitmapCanvasProvider canvas = new BitmapCanvasProvider(new FileOutputStream(file), format, dpi,
					BufferedImage.TYPE_BYTE_BINARY, false, 0);

			// 生成条形码
			bean.generateBarcode(canvas, msg);

			// 结束绘制
			canvas.finish();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

生成二维码:

package barcode4j;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.krysalis.barcode4j.BarcodeGenerator;
import org.krysalis.barcode4j.BarcodeUtil;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.MimeTypes;

public class DataMatrixCodeTest {
	
	public static void main(String[] args) throws Exception {

		BarcodeUtil util = BarcodeUtil.getInstance();
		BarcodeGenerator gen = util.createBarcodeGenerator(buildCfg("datamatrix"));

		OutputStream fout = new FileOutputStream("2dcode.png");
		int resolution = 300;
		BitmapCanvasProvider canvas = new BitmapCanvasProvider(fout, "image/png", resolution,
				BufferedImage.TYPE_BYTE_BINARY, false, 0);

		gen.generateBarcode(canvas, "be the coder");
		canvas.finish();
	}

	private static Configuration buildCfg(String type) {
		DefaultConfiguration cfg = new DefaultConfiguration("barcode");

		// Bar code type
		DefaultConfiguration child = new DefaultConfiguration(type);
		cfg.addChild(child);

		// Human readable text position
		DefaultConfiguration attr = new DefaultConfiguration("human-readable");
//		DefaultConfiguration subAttr = new DefaultConfiguration("placement");
//		subAttr.setValue("bottom");
//		attr.addChild(subAttr);
//		child.addChild(attr);
//		datamatrix code has no human-readable part
//		see http://barcode4j.sourceforge.net/2.1/symbol-datamatrix.html
		
		attr = new DefaultConfiguration("height");
		attr.setValue(50);
		child.addChild(attr);
		attr = new DefaultConfiguration("module-width");
		attr.setValue("0.6");
		child.addChild(attr);
		return cfg;
	}
}

Zxing生成的条形码下边没有数字,borcode4j有

你可能感兴趣的:(JavaSE)