1. 程式人生 > >生成二維碼(QRCode)圖片加LOGO

生成二維碼(QRCode)圖片加LOGO

package com.konland.web;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import com.swetake.util.Qrcode;


/**
 * 生成二維碼(QRCode)圖片
 * @author
GYF * @date 2017年12月18日 下午15:43:17 * @version 1.0 */
public class LogoQrCode { /** * 生成二維碼(QRCode)圖片 * @param content 二維碼圖片的內容 * @param imgPath 存放生成二維碼圖片完整的路徑 * @param logoPath 二維碼圖片中間的logo路徑 * @param type 生成的圖片字尾 */ public static String createQRCode(String content, String imgPath,String logoPath, int
version,String type) { try { if(StringUtils.isNotBlank(imgPath)){ return "儲存圖片的路徑未不存在"; }else if(StringUtils.isNotBlank(logoPath)){ return "儲存圖片的路徑未不存在"; }else if(StringUtils.isNotBlank(content)){ return "二維碼內容為空"
; } Qrcode qrcodeHandler = new Qrcode(); // 設定二維碼排錯率,可選L(7%)、M(15%)、Q(25%)、H(30%),排錯率越高可儲存的資訊越少,但對二維碼清晰度的要求越小 qrcodeHandler.setQrcodeErrorCorrect('Q'); // N代表數字,A代表字元a-Z,B代表其他字元 qrcodeHandler.setQrcodeEncodeMode('B'); // 設定設定二維碼版本,取值範圍1-40,值越大尺寸越大,可儲存的資訊越大 qrcodeHandler.setQrcodeVersion(version); // 圖片尺寸 int imgSize = 67 + 12 * (version - 1); byte[] contentBytes = content.getBytes("gb2312"); BufferedImage image = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB); Graphics2D gs = image.createGraphics(); gs.setBackground(Color.WHITE); gs.clearRect(0, 0, imgSize, imgSize); // 設定影象顏色 > BLACK gs.setColor(Color.BLACK); // 設定偏移量 不設定可能導致解析出錯 int pixoff = 2; // 輸出內容 > 二維碼 if (contentBytes.length > 0 && contentBytes.length < 130) { boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes); for (int i = 0; i < codeOut.length; i++) { for (int j = 0; j < codeOut.length; j++) { if (codeOut[j][i]) { gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3); } } } } else { return "QRCode content bytes length ="+contentBytes.length + " not in [ 0,125]"; } // 例項化一個Image物件。 Image logo = ImageIO.read(new File(logoPath)); int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image .getWidth() * 2 / 10) : logo.getWidth(null), heightLogo = logo .getHeight(null) > image.getHeight() * 2 / 10 ? (image .getHeight() * 2 / 10) : logo.getWidth(null); /** * logo放在中心 */ int x = (image.getWidth() - widthLogo) / 2; int y = (image.getHeight() - heightLogo) / 2; gs.drawImage(logo, x, y, widthLogo, heightLogo, null); gs.dispose(); image.flush(); // 生成二維碼QRCode圖片 File imgFile = new File(imgPath); ImageIO.write(image,type, imgFile); } catch (Exception e) { e.printStackTrace(); return "error"; } return "success"; } public static void main(String[] args) { String imgPath = "E:\\code\\"+new Date().getTime()+".jpg"; String logoPath = "E:\\code\\logo.png"; String encoderContent = "https://www.baidu.com/"; LogoQrCode.createQRCode(encoderContent, imgPath, logoPath, 6,"jpg"); } }