今天看了下二維碼感覺不錯自己也都收弄個了demo,說是demo其實在準系統的基礎上進行修改而已。
1.環境搭建。所需的jar包有
其中為網上參考demo。
其中
為在原始及開源包下載的基礎上進行修改。
2.二維碼顏色修改介紹。
public class MyZxingEncoderHandler {/** * @param contents 產生的圖片的名稱 * @param width 產生的圖片的寬度 * @param height 產生的圖片的高度 * @param imgPath 產生的圖片路徑 */public void encode(String contents, int width, int height, String imgPath,String logoPath) {Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();// 指定錯誤修正等級hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);// 指定編碼格式hints.put(EncodeHintType.CHARACTER_SET, "GBK");try {//設定產生二維碼的類型BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,BarcodeFormat.QR_CODE, width, height, hints);//0xFFE30022 字型色,0xFFF4C2C2背景色MyMatrixToImageWriter.writeToFile(bitMatrix, "png", imgPath,new MyMatrixToImageConfig(0xFFE30022,0xFFF4C2C2),logoPath);} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {String imgPath = "zxing.png";String logoPath = "logo.png";String contents = http://localhost:8080/demo;int width = 300, height = 300;MyZxingEncoderHandler handler = new MyZxingEncoderHandler();handler.encode(contents, width, height, imgPath,logoPath);System.out.println("Michael ,you have finished zxing encode.");}}
/** * 二維碼添加自訂logo(關鍵區段) */ public static void overlapImage(BufferedImage image,String imgPath, String logoPath){ try { BufferedImage logo = ImageIO.read(new File(logoPath)); Graphics2D g = image.createGraphics();
//logo寬高 int width=image.getWidth()/5; int height=image.getHeight()/5;
//logo起始位置,此目的是為logo置中顯示 int x=(image.getWidth()-width)/2; int y=(image.getHeight()-height)/2; g.drawImage(logo, x, y, width, height, null); g.dispose(); ImageIO.write(image, "png", new File(imgPath)); } catch (Exception e) { e.printStackTrace(); } }
其中詳細代碼可以參考MyMatrixToImageWriter.java類
logo:
最後:
文中所用的資源串連為:
點擊開啟連結