java如何使用zxing识别图片条码

      ZXing 是一个开源 Java 类库用于解析多种格局的 1D/2D 条形码。方针是可以或许对QR编码、Data Matrix、UPC的1D条形码进行解码。 

东西/原料

  • 电脑
  • intellij IDEA

第一步:代码实现。

  1. 1

    第一步调:建立springboot项目。

    1、利用IDEA建立springboot项目

    2、利用eclipse建立springboot项目

    3、添加依靠zxing依靠:

            <!--java zxing二维码(可带logo)、条形码生当作-->

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

    2利用建立项目

    2利用建立项目

  2. 2

    第二步调:编纂生当作二维码和条形码的java类

    1、具体代码如下所示:

    import java.awt.image.BufferedImage;

    import java.io.File;

    import java.io.IOException;

    import java.io.OutputStream;


    import javax.imageio.ImageIO;


    import com.google.zxing.common.BitMatrix;


    /**

     * 二维码的生当作需要借助MatrixToImageWriter类,该类是由Google供给的,可以将该类直接拷贝到源码中利用,当然你也可以本身写个

     * 出产条形码的基类

     */

    public class WriteBitMatricToFile {

    private static final int BLACK = 0xFF000000;

    private static final int WHITE = 0xFFFFFFFF;


    private static BufferedImage toBufferedImage(BitMatrix bm) {

    int width = bm.getWidth();

    int height = bm.getHeight();

    BufferedImage image = new BufferedImage(width, height,

    BufferedImage.TYPE_3BYTE_BGR);

    for (int i = 0; i < width; i++) {

    for (int j = 0; j < height; j++) {

    image.setRGB(i, j, bm.get(i, j) ? BLACK : WHITE);

    }

    }

    return image;

    }


    public static void writeBitMatricToFile(BitMatrix bm, String format,

    File file) throws IOException {


    // 生当作二维码或者条形码

    BufferedImage image = toBufferedImage(bm);


    // 设置logo图标

    // 在图片上添加log,若是不需要则不消执行此步调

    LogoConfig logoConfig = new LogoConfig();

    image = logoConfig.LogoMatrix(image);

    try {

    if (!ImageIO.write(image, format, file)) {

    throw new RuntimeException("Can not write an image to file"

    + file);

    }

    } catch (IOException e) {

    e.printStackTrace();

    }

    }


    /**

    * 生当作不带log的二维码或者条形码

    * @param matrix

    * @param format

    * @param stream

    * @throws IOException

    */

    public static void writeToStream(BitMatrix matrix, String format,

    OutputStream stream) throws IOException {

    BufferedImage image = toBufferedImage(matrix);

    if (!ImageIO.write(image, format, stream)) {

    throw new IOException("Could not write an image of format "

    + format);

    }

    }

    }

  3. 3

    第三步调:给图片(二维码和条形码)添加log的java类。

    1、具体代码如下所示:

    import java.awt.BasicStroke;

    import java.awt.Color;

    import java.awt.Graphics2D;

    import java.awt.geom.RoundRectangle2D;

    import java.awt.image.BufferedImage;

    import java.io.File;

    import java.io.IOException;

    import javax.imageio.ImageIO;


    //二维码 添加 logo图标 处置的方式, 仿照微信主动生当作二维码结果,有圆角边框,logo和二维码间有空白区,logo带有灰色边框

    public class LogoConfig {


    /**

    * 设置 logo

    * @param matrixImage

    *            源二维码图片

    * @return 返回带有logo的二维码图片

    * @throws IOException

    * @author Administrator sangwenhao

    */

    public BufferedImage LogoMatrix(BufferedImage matrixImage)

    throws IOException {

    /**

    * 读取二维码图片,并构建画图对象

    */

    Graphics2D g2 = matrixImage.createGraphics();


    int matrixWidth = matrixImage.getWidth();

    int matrixHeigh = matrixImage.getHeight();


    /**

    * 读取Logo图片

    */

    BufferedImage logo = ImageIO.read(new File("E:/file/log.jpg"));


    // 起头绘制图片

    g2.drawImage(logo, matrixWidth / 5 * 2, matrixHeigh / 5 * 2,

    matrixWidth / 5, matrixHeigh / 5, null);// 绘制

    BasicStroke stroke = new BasicStroke(5, BasicStroke.CAP_ROUND,

    BasicStroke.JOIN_ROUND);

    g2.setStroke(stroke);// 设置笔画对象

    // 指心猿意马弧度的圆角矩形

    RoundRectangle2D.Float round = new RoundRectangle2D.Float(

    matrixWidth / 5 * 2, matrixHeigh / 5 * 2, matrixWidth / 5,

    matrixHeigh / 5, 20, 20);

    g2.setColor(Color.white);

    g2.draw(round);// 绘制圆弧矩形


    // 设置logo 有一道灰色边框

    BasicStroke stroke2 = new BasicStroke(1, BasicStroke.CAP_ROUND,

    BasicStroke.JOIN_ROUND);

    g2.setStroke(stroke2);// 设置笔画对象

    RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(

    matrixWidth / 5 * 2 + 2, matrixHeigh / 5 * 2 + 2,

    matrixWidth / 5 - 4, matrixHeigh / 5 - 4, 20, 20);

    g2.setColor(new Color(128, 128, 128));

    g2.draw(round2);// 绘制圆弧矩形


    g2.dispose();

    matrixImage.flush();

    return matrixImage;

    }


    }

  4. 4

    第四步调:生当作二维码和条形码测试代码。

    1、具体代码如下所示:

    import java.io.File;

    import java.io.FileOutputStream;

    import java.io.IOException;

    import java.util.HashMap;


    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.decoder.ErrorCorrectionLevel;


    public class EncodeTest {


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

    EncodeTest test = new EncodeTest();

    // 生当作带log的二维码

    test.qr_code();

    // 生当作不带log的条形码

    test.ean_code();

    }


    /**

    * 二维码

    * @throws IOException

    */

    public void qr_code() throws WriterException, IOException {

            int width = 300;

            int height = 300;

            String text = "https://jingyan.baidu.com/user/npublic?uid=be683ee17853d6d6a312287b";

            String format = "png";

            HashMap<EncodeHintType, Object> hints = new HashMap<>();

            // 指心猿意马纠错品级,纠错级别(L 7%、M 15%、Q 25%、H 30%)

            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            // 内容所利用字符集编码

            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            // 二维码的格局是BarcodeFormat.QR_CODE

            BitMatrix bm = new MultiFormatWriter().encode(text,

                    BarcodeFormat.QR_CODE, width, height, hints);

            // 生当作二维码图片

            // File out = new File("qr_code.png"); //默认项目根目次里

            File out = new File("E:" + File.separator + "file/qr_code.png"); // 指心猿意马输出路径  File.separator解决跨平台

            WriteBitMatricToFile.writeBitMatricToFile(bm, format, out);

        }


    /**

    * 条形码

    * @throws IOException

    */

    public void ean_code() throws WriterException, IOException {

            int width = 200;

            int height = 100;

            String text = "6923450657713";

            String format = "png";

            HashMap<EncodeHintType, String> hints = new HashMap<>();

            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            // 条形码的格局是 BarcodeFormat.EAN_13

            BitMatrix bm = new MultiFormatWriter().encode(text,

                    BarcodeFormat.EAN_13, width, height, hints);

            // 生当作条形码图片

            File out = new File("E:" + File.separator + "file/ean3.png");// 指心猿意马输出路径 // File.separator解决跨平台


            //不需要条形码的log

            WriteBitMatricToFile.writeToStream(bm, format, new FileOutputStream(out));


            //需要条形码的log

            //WriteBitMatricToFile.writeBitMatricToFile(bm, format, out);

        }

    }

  5. 5

    第五步调:读取二维码和条形码测试类。

    1、具体代码如下所示:

    import com.google.zxing.*;

    import com.google.zxing.client.j2se.BufferedImageLuminanceSource;

    import com.google.zxing.common.GlobalHistogramBinarizer;

    import com.google.zxing.common.HybridBinarizer;


    import javax.imageio.ImageIO;

    import java.awt.image.BufferedImage;

    import java.io.File;

    import java.io.FileInputStream;

    import java.util.HashMap;

    import java.util.Map;


    public class DecodeTest {


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


            // 这是二维码图片

            BufferedImage bi = ImageIO.read(new FileInputStream(new File("E:" + File.separator + "file/qr_code.png")));

            if (bi != null) {

                Map<DecodeHintType, String> hints = new HashMap<>();

                hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

                LuminanceSource source = new BufferedImageLuminanceSource(bi);

                // 这里还可所以

                //BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

                BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));

                Result res = new MultiFormatReader().decode(bitmap, hints);

                System.out.println("图片中内容:  "+ res.getText());

                System.out.println("图片中格局:   " + res.getBarcodeFormat());

            }


            // 这是条形码图片

            BufferedImage rs = ImageIO.read(new FileInputStream(new File("E:" + File.separator + "file/ean3.png")));

            if (bi != null) {

                Map<DecodeHintType, String> hints = new HashMap<>();

                hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

                LuminanceSource source = new BufferedImageLuminanceSource(rs);

                // 这里还可所以

                //BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

                BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));

                Result res = new MultiFormatReader().decode(bitmap, hints);

                System.out.println("图片中内容:  "+ res.getText());

                System.out.println("图片中格局:   " + res.getBarcodeFormat());

            }


        }

    }

第二步:功能测试。

  1. 1

    第一步调:生当作二维码和条形码。

    1、生当作含有log的二维码和条形码

    2、生当作没有log的条形码

  2. 2

    第二步调:读取二维码和条形码。

    1、执行DecodeTest本家儿函数main方式

    2、输出读取内容

注重事项

  • zxing版本3.3.0在利用中,解析条形码时报错Exception in thread "main" com.google.zxing.NotFoundException
  • 开辟情况 jdk 1.8 IDEA 2018.2.2 maven:apache-maven-3.5.4
  • 发表于 2019-06-06 20:02
  • 阅读 ( 1293 )
  • 分类:其他类型

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
admin
admin

0 篇文章

作家榜 »

  1. xiaonan123 189 文章
  2. 汤依妹儿 97 文章
  3. luogf229 46 文章
  4. jy02406749 45 文章
  5. 小凡 34 文章
  6. Daisy萌 32 文章
  7. 我的QQ3117863681 24 文章
  8. 华志健 23 文章

联系我们:uytrv@hotmail.com 问答工具