zxing 生成二维码,可设置logo、二维码颜色、白边大小

主要是使用google的zxing 生成二维码,可设置logo、二维码前景色/后景色、白边大小、二维码大小

1、用到jar包

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

2、生成二维码参数类

/**
 * @copyright @2015-2016 Abel-Studio.All Rights Reserved
 */
package com.abel.tools.qrcode;
 
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 
/**
 * @description
 * @author Abel.lin
 * @date 2016年7月10日 下午4:41:41
 */
public class QRCodeParams {
	private String txt;                //二维码内容
	private String qrCodeUrl;          //二维码网络路径
	private String filePath;           //二维码生成物理路径
	private String fileName;           //二维码生成图片名称(包含后缀名)
	private String logoPath;           //logo图片
	private Integer width = 300;           //二维码宽度
	private Integer height = 300;          //二维码高度
	private Integer onColor = 0xFF000000;  //前景色
	private Integer offColor = 0xFFFFFFFF; //背景色
	private Integer margin = 1;            //白边大小,取值范围0~4
	private ErrorCorrectionLevel level = ErrorCorrectionLevel.L;  //二维码容错率
	
	public String getTxt() {
		return txt;
	}
	public void setTxt(String txt) {
		this.txt = txt;
	}
	public String getFilePath() {
		return filePath;
	}
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public Integer getWidth() {
		return width;
	}
	public void setWidth(Integer width) {
		this.width = width;
	}
	public Integer getHeight() {
		return height;
	}
	public void setHeight(Integer height) {
		this.height = height;
	}
	public String getQrCodeUrl() {
		return qrCodeUrl;
	}
	public void setQrCodeUrl(String qrCodeUrl) {
		this.qrCodeUrl = qrCodeUrl;
	}
	public String getLogoPath() {
		return logoPath;
	}
	public void setLogoPath(String logoPath) {
		this.logoPath = logoPath;
	}
	public Integer getOnColor() {
		return onColor;
	}
	public void setOnColor(Integer onColor) {
		this.onColor = onColor;
	}
	public Integer getOffColor() {
		return offColor;
	}
	public void setOffColor(Integer offColor) {
		this.offColor = offColor;
	}
	public ErrorCorrectionLevel getLevel() {
		return level;
	}
	public void setLevel(ErrorCorrectionLevel level) {
		this.level = level;
	}
 
	/**
	 * 返回文件后缀名
	 * @return
	 */
	public String getSuffixName(){
		String imgName = this.getFileName();
		if(imgName != null && !"".equals(imgName)){
			String suffix=fileName.substring(fileName.lastIndexOf(".")+1);
			return suffix;
		}
		return "";
	}
	public Integer getMargin() {
		return margin;
	}
	public void setMargin(Integer margin) {
		this.margin = margin;
	}
}

3、生成二维码工具类

/**
 * @copyright @2015-2016 Abel-Studio.All Rights Reserved
 */
package com.abel.tools.qrcode;
 
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
 
import javax.imageio.ImageIO;
 
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 
/**
 * @description
 * @author Abel.lin
 * @date 2016年7月10日 下午4:41:41
 */
public class QRCodeUtil {
	private static int width = 300;              //二维码宽度
	private static int height = 300;             //二维码高度
	private static int onColor = 0xFF000000;     //前景色
	private static int offColor = 0xFFFFFFFF;    //背景色
	private static int margin = 1;               //白边大小,取值范围0~4
	private static ErrorCorrectionLevel level = ErrorCorrectionLevel.L;  //二维码容错率
    
    /**
     * 生成二维码
     * @param params
     * QRCodeParams属性:txt、fileName、filePath不得为空;
     * @throws QRParamsException
     */
    public static void generateQRImage(QRCodeParams params)throws QRParamsException{
    	if(params == null
			|| params.getFileName() == null
			|| params.getFilePath() == null
			|| params.getTxt() == null){
 
			throw new QRParamsException("参数错误");
		}
    	try{
    		initData(params);
    		
            String imgPath = params.getFilePath();  
            String imgName = params.getFileName(); 
            String txt = params.getTxt();
            
            if(params.getLogoPath() != null && !"".equals(params.getLogoPath().trim())){
            	generateQRImage(txt, params.getLogoPath(), imgPath, imgName, params.getSuffixName());
            }else{
            	generateQRImage(txt, imgPath, imgName, params.getSuffixName());
            }
    	}catch(Exception e){
    		e.printStackTrace();
    	}
            
    }
    
	/**
	 * 生成二维码
	 * @param txt          //二维码内容
	 * @param imgPath      //二维码保存物理路径
	 * @param imgName      //二维码文件名称
	 * @param suffix       //图片后缀名
	 */
	public static void generateQRImage(String txt, String imgPath, String imgName, String suffix){  
         
        File filePath = new File(imgPath);
        if(!filePath.exists()){
        	filePath.mkdirs();
        }
        
        File imageFile = new File(imgPath,imgName);
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();  
        // 指定纠错等级  
        hints.put(EncodeHintType.ERROR_CORRECTION, level);  
        // 指定编码格式  
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); 
        hints.put(EncodeHintType.MARGIN, margin);   //设置白边
        try {  
        	MatrixToImageConfig config = new MatrixToImageConfig(onColor, offColor);
        	BitMatrix bitMatrix = new MultiFormatWriter().encode(txt,BarcodeFormat.QR_CODE, width, height, hints);  
//        	bitMatrix = deleteWhite(bitMatrix);
        	MatrixToImageWriter.writeToPath(bitMatrix, suffix, imageFile.toPath(), config);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }
	
    /**
     * 生成带logo的二维码图片 
     * @param txt          //二维码内容
     * @param logoPath     //logo绝对物理路径
	 * @param imgPath      //二维码保存绝对物理路径
	 * @param imgName      //二维码文件名称
	 * @param suffix       //图片后缀名
     * @throws Exception
     */
    public static void generateQRImage(String txt, String logoPath, String imgPath, String imgName, String suffix) throws Exception{
   
        File filePath = new File(imgPath);
        if(!filePath.exists()){
        	filePath.mkdirs();
        }
        
        if(imgPath.endsWith("/")){
        	imgPath += imgName;
        }else{
        	imgPath += "/"+imgName;
        }
        
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();   
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");    
        hints.put(EncodeHintType.ERROR_CORRECTION, level);  
        hints.put(EncodeHintType.MARGIN, margin);  //设置白边
        BitMatrix bitMatrix = new MultiFormatWriter().encode(txt, BarcodeFormat.QR_CODE, width, height, hints);  
        File qrcodeFile = new File(imgPath);    
        writeToFile(bitMatrix, suffix, qrcodeFile, logoPath);    
    }  
      
    /** 
     *  
     * @param matrix 二维码矩阵相关 
     * @param format 二维码图片格式 
     * @param file 二维码图片文件 
     * @param logoPath logo路径 
     * @throws IOException 
     */  
    public static void writeToFile(BitMatrix matrix,String format,File file,String logoPath) throws IOException {  
        BufferedImage image = toBufferedImage(matrix);  
        Graphics2D gs = image.createGraphics();  
         
        int ratioWidth = image.getWidth()*2/10;
        int ratioHeight = image.getHeight()*2/10;
        //载入logo  
        Image img = ImageIO.read(new File(logoPath)); 
        int logoWidth = img.getWidth(null)>ratioWidth?ratioWidth:img.getWidth(null);
        int logoHeight = img.getHeight(null)>ratioHeight?ratioHeight:img.getHeight(null);
        
        int x = (image.getWidth() - logoWidth) / 2; 
        int y = (image.getHeight() - logoHeight) / 2;
        
        gs.drawImage(img, x, y, logoWidth, logoHeight, null); 
        gs.setColor(Color.black);
        gs.setBackground(Color.WHITE);
        gs.dispose();  
        img.flush();  
        if(!ImageIO.write(image, format, file)){  
            throw new IOException("Could not write an image of format " + format + " to " + file);    
        }  
    }  
      
    public static BufferedImage toBufferedImage(BitMatrix matrix){  
        int width = matrix.getWidth();  
        int height = matrix.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, matrix.get(x, y) ? onColor : offColor);  
            }  
        }  
        return image;     
    } 
    
    public static BitMatrix deleteWhite(BitMatrix matrix){  
        int[] rec = matrix.getEnclosingRectangle();  
        int resWidth = rec[2] + 1;  
        int resHeight = rec[3] + 1;  
      
        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);  
        resMatrix.clear();  
        for (int i = 0; i < resWidth; i++) {  
            for (int j = 0; j < resHeight; j++) {  
                if (matrix.get(i + rec[0], j + rec[1]))  
                    resMatrix.set(i, j);  
            }  
        }  
        return resMatrix;  
    } 
    
    private static void initData(QRCodeParams params){
    	if(params.getWidth() != null){
    		width = params.getWidth();
    	}
    	if(params.getHeight() != null){
    		height = params.getHeight();
    	}
    	if(params.getOnColor() != null){
    		onColor = params.getOnColor();
    	}
    	if(params.getOffColor() != null){
    		offColor = params.getOffColor();
    	}
    	if(params.getLevel() != null){
    		level = params.getLevel();
    	}
    	
    }
}

4、自定义异常类

/**
 * @copyright @2015-2016 Abel-Studio.All Rights Reserved
 */
package com.abel.tools.qrcode;
 
/**
 * @description
 * @author Abel.lin
 * @date 2016年7月10日 下午4:41:41
 */
public class QRParamsException extends Exception {
	private static final long serialVersionUID = 8837582301762730656L;
	public QRParamsException()  {}                //用来创建无参数对象
    public QRParamsException(String message) {        //用来创建指定参数对象
        super(message);                             //调用超类构造器
    }
}

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
zxing是一款非常优秀的开源库,可以帮助我们快速、方便地生成二维码。在使用zxing生成二维码时,我们需要先准备好相关的依赖和jar包,并使用QRCodeWriter类来生成普通的二维码。具体的生成过程如下: 1. 首先,我们需要下载zxing的jar包,并将其导入到项目中。 2. 在生成二维码的代码中,我们需要创建一个QRCodeWriter对象,用于生成二维码。然后,我们需要准备一些参数,如二维码的内容、宽度、高度等。这些参数会被传递给QRCodeWriter对象的encode方法。 3. 在生成二维码之前,我们可以设置一些可选的参数,如编码类型、字符集等。可以使用Hashtable对象来存储这些参数。 4. 调用QRCodeWriter对象的encode方法,传入参数,即可生成一个BitMatrix对象,它表示了一个二维码的矩阵。 5. 最后,我们可以将BitMatrix对象转换为图片,并保存到指定的文件路径中。 以上就是使用zxing生成二维码的基本步骤。如果需要生成带有Logo的二维码,我们可以使用MatrixToImageConfig类来实现。无论是生成普通的二维码还是带有Logo的二维码zxing都是一个非常实用的工具。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [使用zxing生成二维码](https://blog.csdn.net/qinshengfei/article/details/131142998)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [二维码的知识 看这一篇就够了 使用zxing进行二维码的生成](https://blog.csdn.net/q15976405716/article/details/107402967)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值