二维码生成工具类java版

注意:这里我不提供所需jar包的路径,我会把所有引用的jar包显示出来,大家自行Google

package com.net.util;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/********************************************************************************
 * Description: 二维码制作工具类
 * @author zhangdi
 * @version 1.0
 */
public class QRCodeUtil {
    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO宽度
    private static final int WIDTH = 60;
    // LOGO高度
    private static final int HEIGHT = 60;  

    /**
     * 生成二维码
     * @param content   源内容
     * @param imgPath   生成二维码保存的路径
     * @param needCompress  是否要压缩
     * @return      返回二维码图片
     * @throws Exception
     */
    private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }
        // 插入图片
        QRCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }  

    /**
     * 在生成的二维码中插入图片
     * @param source
     * @param imgPath
     * @param needCompress
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }  

    /**
     * 生成带logo二维码,并保存到磁盘
     * @param content
     * @param imgPath   logo图片
     * @param destPath
     * @param needCompress
     * @throws Exception
     */
    public static String encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        mkdirs(destPath);
        String file = new Random().nextInt(99999999) + ".jpg";//生成随机文件名
        ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
        return file;
    }  

    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir。(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }  

    public static void encode(String content, String imgPath, String destPath) throws Exception {
        QRCodeUtil.encode(content, imgPath, destPath, false);
    }  

    public static void encode(String content, String destPath, boolean needCompress) throws Exception {
        QRCodeUtil.encode(content, null, destPath, needCompress);
    }  

    public static void encode(String content, String destPath) throws Exception {
        QRCodeUtil.encode(content, null, destPath, false);
    }  

    public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
            throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        ImageIO.write(image, FORMAT_NAME, output);
    }  

    public static void encode(String content, OutputStream output) throws Exception {
        QRCodeUtil.encode(content, null, output, false);
    }  

    /**
     * 从二维码中,解析数据
     * @param file  二维码图片文件
     * @return   返回从二维码中解析到的数据值
     * @throws Exception
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }  

    public static String decode(String path) throws Exception {
        return QRCodeUtil.decode(new File(path));
    }
//    try {
////String text = "http://weifeng.nethangzhou.com/wf/weixin/getUserInfoCode";
//String text = "http://www.lechuan100.com/plugin.php?id=haven_article&mod=my&aid=21";
////生成带logo 的二维码
////QRCodeUtil.encode(text, "d:/730.png", "d:/wfqrcode", true);
////生成不带logo 的二维码
//QRCodeUtil.encode(text,"","d:/wfqrcode",true);
//
////指定二维码图片,解析返回数据
////System.out.println(QRCodeUtil.decode("D:/WPS/75040887.jpg"));
//} catch (Exception e) {
//e.printStackTrace();
//}
}  
时间: 2024-08-02 02:49:43

二维码生成工具类java版的相关文章

二维码生成工具类

1 package com.ideal.common.util; 2 3 import java.awt.image.BufferedImage; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileNotFoundException; 7 import java.io.FileOutputStream; 8 import java.util.UUID; 9 10 import net.glx

zxing二维码生成工具类

图片生成工具生成 1.支持多中形式的图片,二维码,条形码 2.支持一张图片多个二维码 3.支持二维码图片上加logo 4.支持图片头部底部添加文字描述 public class ZxingEncoderUtil { private static final String CHARSET = "utf-8"; private static final String FORMAT = "JPG"; private static Font font = null; /**

Java版本logo 名片二维码生成工具类

 package com.zzq; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Shape; import java.awt.font.FontRenderContext; import java.awt.ge

Java 二维码生成工具类

public class QRcodeUtils { /** * 容错率等级 L */ public static final char CORRECT_L = 'L'; /** * 容错率等级 M */ public static final char CORRECT_M = 'M'; /** * 容错率等级 Q */ public static final char CORRECT_Q = 'Q'; /** * 容错率等级 H */ public static final char CORR

vue项目条形码和二维码生成工具试用

项目开发需要,优惠券分不同类型,简单的使用id生成条形码供店铺使用,麻烦点的需要多个字段的就需要使用二维码来展示了,对应的效果如下 条形码(一维码)使用工具code128 需引入code128.js 和对应的 code123.css, 具体代码可以看 https://www.jb51.net/article/103472.htm 由于项目是vue开发,所以code128.js 稍微改一下,export 出createBarcode接口 export default function create

python3调用NowAPI接口实现二维码生成工具

本人python学习菜鸟一枚,随着对python的学习,感觉python越来越好玩了,上次用接口查询IP地址后,又看到有道词典查询.二维码生成等接口相关的方法,并对其做了简单的尝试,确实是挺好玩的.所以将整个过程记录下来.分享在此,供大家一起交流学习. 1.基本环境 系统:windows 7 开发环境:pycharm python3 相关的模块和库  urlib  urllib.parse 2.NowAPI简单的介绍 NowAPI是一家 数据服务公司,提供大量的数据接口,对于我们这种学习的菜鸟来

java二维码生成工具

import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Hashtable; import java.util.Map; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import

java基于谷歌开发的zxing包开发的二维码生成工具

不得不说,二维码的应用越来越广泛了.废话不多说了.. 此处采用的jar不多,只用zxing包里面的core.jar包即可,大家自行下载, 如果是百度云盘,地址为:http://pan.baidu.com/s/1eQeWFaq 以后很多的博客资源将会更新到这个地址中,大家尽量把资源转移自己的盘,防止链接某天突然挂了. 实例: genQRCode(String content,String url),其中url绝对路径,就是这个类的调用方法,返回值二维码文件名,生成png格式(如需其他,自行更改),

[二维码生成和解析][Java]

首先必须的jar包文件:百度云盘下载   Qrcode.jar    Qrcode_Swetake.jar 这两个就是我们的主角 学习之前可以简单了解一下:二维码原理 新建JavaProject    新建lib文件夹 将jar文件复制进去,选中jar文件右键BuildPath -- Add to BuildPath (旁白:这么简单的操作你都还要讲!) 进入正题:   代码如下:    为方面同学理解 注释较多 请理解  如感不适  请见谅  (旁白:废话太多了 我要看代码!) 生成Qrcod