用zxing生成条形码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cnhome/article/details/82145444

ZXing还是十分强大的,给我们写代码省去了不少事情。先来看看他支持的编码:

1D product 1D industrial 2D
UPC-A Code 39 QR Code
UPC-E Code 93 Data Matrix
EAN-8 Code 128 Aztec (beta)
EAN-13 Codabar PDF 417 (beta)
ITF MaxiCode
RSS-14
RSS-Expanded

言归正传,抓几个例子来看一看如何生成Code 128的条形码。

/**
 * A method for generating a barcode of some text
 *
 * @param string        the string to be converted to barcode, will be a bid in this case
 * @return              an image representing the barcode to be drawn on a ballot
 */
public static BufferedImage getBarcode(String string){
    /* Try to encode the string as a barcode */
    try {
        Code128Writer writer = new Code128Writer();
        BitMatrix bar = writer.encode(string, BarcodeFormat.CODE_128, 264, 48, new HashMap<EncodeHintType,Object>());
        return MatrixToImageWriter.toBufferedImage(bar);
    }
    catch (WriterException e){ throw new RuntimeException(e); }
}

再来一个看得仔细点:

public BufferedImage getCode128(String strCode128) {
    BitMatrix bitMatrix;
    try {
        //  Write Barcode
        bitMatrix = new Code128Writer().encode(strCode128, BarcodeFormat.CODE_128, 195, 40, null);
        MatrixToImageWriter.toBufferedImage(bitMatrix);
        //System.out.println("Code128 Barcode Generated.");
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    } catch (Exception e) {
        System.out.println("Exception Found." + e.getMessage());
    }
    return null;
}

老外也给了一个不错的例子,往上绘制相关编码,值得一看:

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Hashtable;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

// ...
// vars width and height have image width and height (int)
// var barcodeMessage has the text under the barcode

// text
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); // aux implementation
Graphics2D g2d = img.createGraphics();
Font font = new Font("Times", Font.PLAIN, 11);
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
int textWidth = fm.stringWidth(barcodeMessage);
int textHeight = fm.getHeight();
g2d.dispose();
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g2d = img.createGraphics();
g2d.setColor(backgroundColor);
g2d.fillRect(0, 0, width, height);
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2d.setFont(font);
fm = g2d.getFontMetrics();
g2d.setColor(textColor);
g2d.drawString(barcodeMessage, Math.round(Math.floor((width-textWidth)/2))-2, height-fm.getAscent());
g2d.dispose();

// barcode
Code128Writer code128Writer = new Code128Writer();
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
BitMatrix bitMatrix = code128Writer.encode(barcodeMessage, BarcodeFormat.CODE_128, width, height-textHeight-(2*fm.getAscent()), hintMap);

// Make the BufferedImage that are to hold the Code128
int matrixWidth = bitMatrix.getWidth();
int matrixHeight = bitMatrix.getHeight();

Graphics2D graphics = (Graphics2D) img.getGraphics();
graphics.setColor(textColor);
for (int i = 0; i < matrixWidth; i++) {
    for (int j = 0; j < matrixHeight; j++) {
        if (bitMatrix.get(i, j)) {
            graphics.fillRect(i, j+fm.getAscent(), 1, 1);
        }
    }
}

万事皆容易,只是看你要做到什么程度了。

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication1;

/**
*
* @author pc
*/
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Writer;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.pdf417.encoder.PDF417Writer;
import com.google.zxing.qrcode.QRCodeWriter;
import java.io.File;
import java.io.FileOutputStream;

public class barcode {
    public static void main(String[] args) {
        BitMatrix bitMatrix;
        Writer writer = new QRCodeWriter();
        try {
            //  Write Barcode
            bitMatrix = new Code128Writer().encode(“123456789”, BarcodeFormat.CODE_128, 150, 80, null);
            MatrixToImageWriter.writeToStream(bitMatrix, “png”, new FileOutputStream(new File(“D://code12kk8_123456789.png”)));
            System.out.println(“Code128 Barcode Generated.”);
            //  Write QR Code
            bitMatrix = writer.encode(“123456789”, BarcodeFormat.QR_CODE, 200, 200);
            MatrixToImageWriter.writeToStream(bitMatrix, “png”, new FileOutputStream(new File(“D://qrcode_123456789.png”)));
            System.out.println(“QR Code Generated.”);
            //  Write PDF417
            writer = new PDF417Writer();
            bitMatrix = writer.encode(“123456789”, BarcodeFormat.PDF_417, 80, 150);
            MatrixToImageWriter.writeToStream(bitMatrix, “png”, new FileOutputStream(new File(“D://pdf417_123456789.png”)));
            System.out.println(“PDF417 Code Generated.”);
        } catch (Exception e) {
            System.out.println(“Exception Found.” + e.getMessage());
        }
    }
}

猜你喜欢

转载自blog.csdn.net/cnhome/article/details/82145444