java生成条形码和二维码


使用的包 zxingbarcode4j

MAVEN配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>WEEK6</groupId>
  <artifactId>WEEK6</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  
  	<properties>
  	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<maven.compiler.source>1.8</maven.compiler.source>
	<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

  
	 <repositories>
		<repository>
	        <id>central</id>
	        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
	    </repository>
	</repositories>
	
  	<pluginRepositories>
	    <pluginRepository>
	        <id>central</id>
	        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
	    </pluginRepository>
	</pluginRepositories>
	
	
	<dependencies>
	<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
	<dependency>
	    <groupId>com.google.zxing</groupId>
	    <artifactId>core</artifactId>
	    <version>3.3.3</version>
	</dependency>
  	<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
	<dependency>
	    <groupId>com.google.zxing</groupId>
	    <artifactId>javase</artifactId>
	    <version>3.3.3</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/net.sf.barcode4j/barcode4j -->
	<dependency>
	    <groupId>net.sf.barcode4j</groupId>
	    <artifactId>barcode4j</artifactId>
	    <version>2.1</version>
	</dependency>  	
	<!-- https://mvnrepository.com/artifact/org.apache.avalon.framework/avalon-framework-api -->
	<dependency>
	    <groupId>org.apache.avalon.framework</groupId>
	    <artifactId>avalon-framework-api</artifactId>
	    <version>4.3.1</version>
	</dependency>
	
	</dependencies>
</project>

生成条形码

法一:

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<DecodeHintType, Object> 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"));
    }
}

法二:

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 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<EncodeHintType, Object> 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<DecodeHintType, Object> 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"));
    }
}

法二:

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;
	}
}

结果:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值