qrcode二维码生成,可插图片文字

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.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.swetake.util.Qrcode;

所需jar包下载:Qrcode.jar和core.jar
public class QRCodeUtil {
// 二维码宽度
    private final static int QRCODE_WIDTH = 300;
    // 二维码高度
    private final static int QRCODE_HEIGHT = 300;
    // LOGO宽度
    private final static int LOGO_WIDTH = 60;
    // LOGO高度
    private final static int LOGO_HEIGHT = 60;
    

 /**

*创建二维码,文字内容和中间logo没有用null替换

*/

   public static BufferedImage createComplexQRCode(String qrData, String note, String logoPath) throws Exception{
   
    BufferedImage image = QRCodeUtil.createSimpleQRCode(qrData);//创建一个简单的二维码
   
    image = (BufferedImage) QRCodeUtil.flexible(image, QRCODE_WIDTH, QRCODE_HEIGHT);//调整二维码的大小
   
    image = QRCodeUtil.addLogo(image, logoPath);//添加logo
   
    image = QRCodeUtil.addNote(image, note);//添加底部文字
   
    image.flush();
    return image;
    }

     
    /**
     * 创建一个简单的二维码
     * @param qrData二维码内容,不能为空或者""
     * @return BufferedImage
     * @throws Exception
     */
    public static BufferedImage createSimpleQRCode(String qrData) throws Exception{
    if(qrData==null||"".equals(qrData)){
    return null;
    }
    Qrcode x = new Qrcode();
x.setQrcodeErrorCorrect('M');//纠错等级
x.setQrcodeEncodeMode('B');//N代表数字,A代表a~z,B代表其他字符
x.setQrcodeVersion(7);//版本

int width = 67 + 12 * ( 7 - 1 );//固定写法
int height = 67 + 12 * ( 7 - 1 );//固定写法

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();

g.setBackground(Color.WHITE);
g.setColor(Color.BLACK);
g.clearRect(0, 0, width, height);

int pixoff = 2;//偏移量

byte[] d = qrData.getBytes("gb2312");
if (d.length>0 && d.length <120){
   boolean[][] s = x.calQrcode(d);
   for (int i=0;i    for (int j=0;j    if (s[j][i]) {
    g.fillRect(j*3 + pixoff,i*3 + pixoff,3,3);
    }
    }
   }
}else{
return null;
}
g.dispose();
return image;
    }
    
/**
* BufferedImage的伸缩
* @return
*/
public static Image flexible(Image image, int width, int height){
// 获取一个自定义宽高的图像实例
Image src = image.getScaledInstance(width, height,Image.SCALE_DEFAULT);
//缩放图像
   BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
   Graphics2D g = tag.createGraphics();
        g.drawImage(src, 0, 0, null);// 绘制缩小后的图
        g.dispose();
return tag;

}
    /**
     * 添加logo
     * @param image 原二维码
     * @param logoPath logo地址
     * @return 带logo的图像
     * @throws Exception
     */
    public static BufferedImage addLogo(BufferedImage image, String logoPath) throws Exception{
    File file = new File(logoPath);
    if (!file.exists()) {
            System.err.println(logoPath+"   该文件不存在!(二维码logo)");
            return image;
        }
    Image logo = ImageIO.read(file);
        int lgwidth = logo.getWidth(null);
        int lgheight =logo.getHeight(null);
        if (lgwidth > LOGO_WIDTH)  lgwidth =LOGO_WIDTH; 
        if (lgheight > LOGO_HEIGHT) lgheight = LOGO_HEIGHT;
      
        //缩放LOGO
        logo =  QRCodeUtil.flexible(logo, lgwidth, lgheight);
        
        // 插入LOGO
        Graphics2D graph = image.createGraphics();
        int i = (QRCODE_WIDTH - lgwidth) / 2;
        int j = (QRCODE_HEIGHT - lgheight) / 2;
        graph.drawImage(logo, i, j, lgwidth, lgheight, null);
        Shape shape = new RoundRectangle2D.Float(i, j, lgwidth, lgwidth, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
return image;
    }
    
    /**
     * 给二维码下方添加说明文字
     * @param image原二维码
     * @param note说明文字
     * @return 带说明文字的二维码
     */
public static BufferedImage addNote(BufferedImage image,String note){
    Image src = image.getScaledInstance(300, 300,Image.SCALE_DEFAULT);
    BufferedImage tag;
    if (note.length()<=16){
    tag = new BufferedImage(300, 322,BufferedImage.TYPE_INT_RGB);
    }else{
    tag = new BufferedImage(300, 345,BufferedImage.TYPE_INT_RGB);  
    }
    
    Graphics g1 = tag.getGraphics();//设置低栏白边
    
    Graphics2D g2 = tag.createGraphics();//设置文字
    Font font = new Font("微软雅黑",Font.BOLD,18);
    g2.setFont(font);
    g2.setColor(Color.BLACK);
    if (note.length()<=16) {
    g1.fillRect(0, QRCODE_HEIGHT, QRCODE_WIDTH, 22);
    g2.drawString(note,QRCODE_WIDTH/2-note.length()*8-14, QRCODE_HEIGHT+font.getSize());     
}else{
g1.fillRect(0, QRCODE_HEIGHT, QRCODE_WIDTH, 45);
g2.drawString(note.substring(0, 16),5, QRCODE_HEIGHT+font.getSize());
g2.drawString(note.substring(16,note.length()), QRCODE_WIDTH/2-(note.length()-16)*8-14, QRCODE_HEIGHT+font.getSize()*2+4);
}
    g1.drawImage(src, 0, 0, null);
    g1.dispose();
    g2.dispose();
    image = tag;
    image.flush();
    return image;
}

/**
* 根据文件路径读取二维码
* @param filePath二维码路径
* @return 读取结果
* @throws Exception
*/
public static String readQRCode(String filePath) throws Exception{
return QRCodeUtil.readQRCode(new File(filePath));
}

/**
* 根据BufferedImage 读取二维码
* @param filePath二维码路径
* @return 读取结果
* @throws Exception
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String readQRCode(File file) throws Exception{

BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        image = image.getSubimage(0, 0, QRCODE_WIDTH, QRCODE_HEIGHT);
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
                image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, "gb2312");
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
}

}

你可能感兴趣的:(java)