前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用zxing生成二维码不带logo

使用zxing生成二维码不带logo

作者头像
故久
发布2019-12-02 22:26:19
9420
发布2019-12-02 22:26:19
举报
文章被收录于专栏:故久故久

一、首先在maven中添加一下jar包

代码语言:javascript
复制
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.0</version>
</dependency>

然后新建个工具类 QrcodeUtil

代码语言:javascript
复制
// 图片宽度的一半
private static final int width = 500;
private static final int height = 500;
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
//生成二维码存放路径
private static final String destImagePath="d:\\qrcode.jpg";
//扫描二维码跳转页面
private static final String content="http://www.baidu.com";

// 二维码写码器
private static MultiFormatWriter multiWriter = new MultiFormatWriter();
代码语言:javascript
复制
/**
 * 生成二维码
 *
 * @param content       要生成二维码的内容
 * @param width         二维码的宽度
 * @param height        二维码的高
 * @param destImagePath 生成二维码图片的路径
 * @return 是否生成成功
 */
public static boolean encode(String content, int width, int height, String destImagePath) {
    try {
        long startTime = System.currentTimeMillis();
        File destImagePaths = new File(destImagePath);
        //生成二维码图片文件(不带LOGO)
        ImageIO.write(genQrcode(content, width, height), "jpg",destImagePaths );
        System.out.println("生成成功!");
        System.out.println("耗时: " + (System.currentTimeMillis()-startTime)/1000.0 + "s");
        System.out.println("生成文件路径: " + destImagePaths.getAbsolutePath());
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
代码语言:javascript
复制
/**
 * 生成二维码图片文件(不带LOGO)
 *
 * @param content 要生成二维码的内容
 * @param width   二维码的高度
 * @param height  二维码的宽度
 * @return 二维码图片
 * @throws WriterException 异常
 */
private static BufferedImage genQrcode(String content, int width, int height) throws WriterException {
    Map<EncodeHintType, String> hints = new HashMap<>();
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

    //根据高度和宽度生成像素矩阵
    BitMatrix bitMatrix = multiWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

    BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < bitMatrix.getWidth(); x++) {
        for (int y = 0; y < bitMatrix.getHeight(); y++) {
            //填充黑白两色
            image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
        }
    }
    return image;
}

main方法

代码语言:javascript
复制
public static void main(String[] args) {
    // 依次为内容,宽,长,储存路径
    QrcodeUtil.encode(content, width, height, destImagePath);
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档