Java zxing生成条形码和二维吗代码实例

时间:2021-05-20

在如今的生活中,二维码随处可见,二维码的出现既减少了宣传纸张的浪费,又方便了人们的生活。这一篇我来说说 Java 利用第三方 Jar 包 zxing 生成二维码。

依赖

<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version></dependency><dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.3</version></dependency>

生成二维码

package code;import com.google.zxing.*;import com.google.zxing.common.BitMatrix;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import org.apache.commons.codec.binary.Base64;import org.apache.commons.codec.binary.Base64OutputStream;import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.io.*;import java.util.HashMap;import java.util.Map;public class QRCodeKit { public static final String QRCODE_DEFAULT_CHARSET = "UTF-8"; public static final int QRCODE_DEFAULT_HEIGHT = 300; public static final int QRCODE_DEFAULT_WIDTH = 300; private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; public static void main(String[] args) throws IOException, NotFoundException { String data = "https://mon.HybridBinarizer; /** * ZXing条形码编码/解码 */public class ZxingCode { /** * 条形码编码 * * @param contents * @param width * @param height * @param imgPath */ public static void encode(String contents, int width, int height, String imgPath) { int codeWidth = 3 + // start guard (7 * 6) + // left bars+ // middle guard (7 * 6) + // right bars 3; // end guard codeWidth = Math.max(codeWidth, width); try { BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,BarcodeFormat.EAN_13, codeWidth, height, null); MatrixToImageWriter.writeToFile(bitMatrix, "png", new File(imgPath)); } catch (Exception e) { e.printStackTrace(); } } /** * 条形码解码 * * @param imgPath * @return String */ public static String decode(String imgPath) { BufferedImage image = null; Result result = null; try { image = ImageIO.read(new File(imgPath)); if (image == null) { System.out.println("the decode image may be not exit."); } LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); result = new MultiFormatReader().decode(bitmap, null); return result.getText(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * @param args */ public static void main(String[] args) { String imgPath = "F:/zxing_EAN-13.png"; String contents = "6926557300360"; int width = 105, height = 50; encode(contents, width, height, imgPath); System.out.println("finished zxing EAN-13 encode."); String decodeContent = decode(imgPath); System.out.println("解码内容如下:" + decodeContent); System.out.println("finished zxing EAN-13 decode."); }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章