java 二维码条形码操作相关工具类

导包

		<!-- 二维码生成工具 -->
        <dependency>
            <groupId>com.github.liuyueyi.media</groupId>
            <artifactId>qrcode-plugin</artifactId>
            <version>2.6.3</version>
        </dependency>

工具类

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeGenWrapper;
import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeOptions;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
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;

/**
 * 二维码条形码操作相关工具类
 *
 * @author ycs
 */
public class YcsQrBarCodeUtils {

    public static final int LOGO_RATE = 10;

    public static final String FORMAT = "png";

    /**
     * 条形码最小宽度98
     */
    public static final int MIN_BARCODE_WIDTH = 98;

    /**
     * 创建二维码
     *
     * @param content  要写入二维码的内容
     * @param size     二维码大小,通常为300左右
     * @param preColor 图片前景色
     * @param logoImg  logo图片,可以为:null
     * @return BufferedImage, 可以使用 ImageIO.write() 输出
     */
    public static BufferedImage createQRCode(String content, int size, Color preColor, BufferedImage logoImg) {

        try {
            QrCodeGenWrapper.Builder builder = QrCodeGenWrapper.of(content)
                    .setW(size)
                    .setH(size)
                    // 使用检测图片代替检测点
                    //  .setDetectImg(logoPath)
                    // 背景色, 默认白色
                    .setDrawBgColor(0xffffffff)
                    // 前景色
                    .setDrawPreColor(preColor)
                    // 容错率
                    .setErrorCorrection(ErrorCorrectionLevel.M)
                    .setDrawStyle(QrCodeOptions.DrawStyle.CIRCLE)
                    .setDrawEnableScale(true);
            if (logoImg != null) {
                // Logo背景色
                builder.setLogoBgColor(Color.LIGHT_GRAY)
                        .setLogo(logoImg)
                        // 占比, 默认10%
                        .setLogoRate(LOGO_RATE)
                        // Logo样式
                        .setLogoStyle(QrCodeOptions.LogoStyle.CIRCLE);
            }
            return builder.asBufferedImage();
        } catch (Exception e) {
            throw new RuntimeException("生成二维码失败!content = "
                    + content + ", size = " + size + ", preColor = " + preColor + "\n" + e);
        }
    }

    /**
     * 解析二维码
     *
     * @param image 二维码图片, 可以使用 ImageIO.read() 创建
     * @return
     */
    public static String parseQRCode(BufferedImage image) {
        try {
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Map<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(bitmap, hints);
            return result.getText();
        } catch (Exception e) {
            throw new RuntimeException("解析二维码失败!" + "\n" + e);
        }
    }

    /**
     * 把传入的原始图像按高度和宽度进行等比缩放
     *
     * @param srcImage  原始图像
     * @param height    目标高度
     * @param width     目标宽度
     * @param hasFiller 比例不对时是否需要补白:true-补白;
     * @return
     */
    public static BufferedImage scale(BufferedImage srcImage, int height, int width, boolean hasFiller) {
        Image destImage = srcImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
        // 计算比例
        if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
            // 缩放比例
            double ratio = 0.0;
            if (srcImage.getHeight() > srcImage.getWidth()) {
                ratio = (new Integer(height)).doubleValue() / srcImage.getHeight();
            } else {
                ratio = (new Integer(width)).doubleValue() / srcImage.getWidth();
            }
            AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
            destImage = op.filter(srcImage, null);
        }
        // 补白
        if (hasFiller) {
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphic = image.createGraphics();
            graphic.setColor(Color.white);
            graphic.fillRect(0, 0, width, height);
            if (width == destImage.getWidth(null)) {
                graphic.drawImage(destImage,
                        0, (height - destImage.getHeight(null)) / 2,
                        destImage.getWidth(null), destImage.getHeight(null),
                        Color.white, null);
            } else {
                graphic.drawImage(destImage,
                        (width - destImage.getWidth(null)) / 2, 0,
                        destImage.getWidth(null), destImage.getHeight(null),
                        Color.white, null);
            }
            graphic.dispose();
            destImage = image;
        }
        return (BufferedImage) destImage;
    }

    /**
     * 创建条形码
     *
     * @param content
     * @param width
     * @param height
     * @param outputStream
     */
    public static void createBarcode(String content, int width, int height, OutputStream outputStream) {
        width = Math.max(MIN_BARCODE_WIDTH, width);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter()
                    .encode(content, BarcodeFormat.EAN_13, width, height, null);
            MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, outputStream);
        } catch (Exception e) {
            throw new RuntimeException("创建条形码失败!content = " + content + "\n" + e);
        }
    }

    /**
     * 解析条形码
     *
     * @param image 条形码图片, 可以使用 ImageIO.read() 创建
     * @return
     */
    public static String parseBarcode(BufferedImage image) {
        try {
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result result = new MultiFormatReader().decode(bitmap, null);
            return result.getText();
        } catch (Exception e) {
            throw new RuntimeException("解析条形码失败!" + "\n" + e);
        }
    }
}

测试

/**
 * @author ycs
 */
public class SelfTest {
    private File desktopDir;
    /**
     * 系统桌面路径
     */
    private String desktopPath;

    @Before
    public void desktopDirTest() {
        desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
        desktopPath = desktopDir.getAbsolutePath();
    }

    @Test
    public void QrBarUtils() throws IOException {
        BufferedImage logoImg = ImageIO.read(new File(desktopPath + "/base64.jpg"));
        logoImg = YcsQrBarCodeUtils.scale(logoImg, 80, 80, true);
        BufferedImage qrCode = YcsQrBarCodeUtils.createQRCode(
                "http://localhost:8080/test", 500, Color.RED, logoImg);
        ImageIO.write(qrCode, "png", new File(desktopPath + "/code.png"));

//        BufferedImage read = ImageIO.read(new File(desktopPath + "/code.png"));
//        System.out.println(YcsQrBarCodeUtils.parseQRCode(read));

//        OutputStream outputStream = new FileOutputStream(desktopPath + "/bar.png");
//        YcsQrBarCodeUtils.createBarcode("6923450657713", 105, 50, outputStream);
//        System.out.println("断点");
//        outputStream.close();

//        BufferedImage read = ImageIO.read(new File(desktopPath + "/bar.png"));
//        System.out.println(YcsQrBarCodeUtils.parseBarcode(read));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜长思

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值