package com.company.utils; 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.FileInputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Random; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.Binarizer; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.EncodeHintType; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.MultiFormatWriter; import com.google.zxing.Result; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; /** * 二維碼工具類 二維碼生成 解析 帶圖片與不帶圖片的二維碼 * */ public class QrcodeUtils { // 默認寬為300 private static Integer WIDTH = 300; // 默認高為300 private static Integer HEIGHT = 300; // 二維碼尺寸 private static final int QRCODE_SIZE = 300; // 默認二維碼圖片格式 private String IMAGEFORMAT = "png"; private static final String IMAGE_FORMAT= "JPG"; // 默認二維碼字符編碼 private static String CHARTYPE = "utf-8"; // 默認二維碼的容錯級別 private ErrorCorrectionLevel corretionLevel = ErrorCorrectionLevel.H; // 二維碼與圖片的邊緣 private static Integer MARGIN = 1; // 二維碼參數 private Map<EncodeHintType, Object> encodeHits = new HashMap<EncodeHintType,Object>(); public QrcodeUtils(Integer width, Integer height, String imageFormat, String charType, ErrorCorrectionLevel corretionLevel, Integer margin) { if (WIDTH != null) { this.WIDTH = WIDTH; } if (HEIGHT != null) { this.HEIGHT = HEIGHT; } if (IMAGEFORMAT != null) { this.IMAGEFORMAT = IMAGEFORMAT; } if (CHARTYPE != null) { this.CHARTYPE = CHARTYPE; } if (corretionLevel != null) { this.corretionLevel = corretionLevel; } if (MARGIN != null) { this.MARGIN = MARGIN; } } public QrcodeUtils(Integer width, Integer height, String imageFormat, String charType, ErrorCorrectionLevel corretionLevel) { this(width, height, imageFormat, charType, corretionLevel, null); } public QrcodeUtils(Integer width, Integer height, String imageFormat, String charType, Integer margin) { this(width, height, imageFormat, charType, null, margin); } public QrcodeUtils(Integer width, Integer height, String imageFormat, String charType) { this(width, height, imageFormat, charType, null, null); } public QrcodeUtils(Integer width, Integer height, String imageFormat) { this(width, height, imageFormat, null, null, null); } public QrcodeUtils(Integer width, Integer height) { this(width, height, null, null, null, null); } public QrcodeUtils() { } // 初始化二維碼的參數 private void initialParamers() { // 字符編碼 encodeHits.put(EncodeHintType.CHARACTER_SET, this.CHARTYPE); // 容錯等級 L、M、Q、H 其中 L 為最低, H 為最高 encodeHits.put(EncodeHintType.ERROR_CORRECTION, this.corretionLevel); // 二維碼與圖片邊距 encodeHits.put(EncodeHintType.MARGIN, MARGIN); } // 得到二維碼圖片 // public BufferedImage getBufferedImage(String content) { // initialParamers(); // BufferedImage bufferedImage = null; // try { // BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width, // this.height, this.encodeHits); // bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix); // } catch (WriterException e) { // e.printStackTrace(); // return null; // } // return bufferedImage; // } // 將二維碼保存到輸出流中 // public void writeToStream(String content, OutputStream os) { // initialParamers(); // try { // BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width, this.height, // this.encodeHits); // MatrixToImageWriter.writeToStream(matrix, this.imageFormat, os); // } catch (Exception e) { // e.printStackTrace(); // } // } // 將二維碼圖片保存為文件 // public void createQrImage(String content, File file) { // initialParamers(); // try { // BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.width, this.height,this.encodeHits); // MatrixToImageWriter.writeToFile(matrix, this.imageFormat, file); // } catch (Exception e) { // e.printStackTrace(); // } // } // 將二維碼圖片保存到指定路徑 public void createQrImage(String content, String path) { initialParamers(); try { BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, this.WIDTH, this.HEIGHT,this.encodeHits); MatrixToImageWriter.writeToFile(matrix, this.IMAGEFORMAT, new File(path)); } catch (Exception e) { e.printStackTrace(); } } //識別圖片二維碼 public String decodeQrImage(File file){ String content=null; try { BufferedImage bufferedImage=ImageIO.read(new FileInputStream(file)); LuminanceSource source=new BufferedImageLuminanceSource(bufferedImage); Binarizer binarizer=new HybridBinarizer(source); BinaryBitmap image=new BinaryBitmap(binarizer); Map<DecodeHintType,Object> decodeHits=new HashMap<DecodeHintType,Object>(); decodeHits.put(DecodeHintType.CHARACTER_SET, this.CHARTYPE); Result result=new MultiFormatReader().decode(image, decodeHits); content=result.getText(); }catch (Exception e) { e.printStackTrace(); } return content; } 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, CHARTYPE); 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; } // 插入圖片 QrcodeUtils.insertImage(image, imgPath, needCompress); return image; } 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(); } public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception { BufferedImage image = QrcodeUtils.createImage(content, imgPath, needCompress); mkdirs(destPath); String file = new Random().nextInt(99999999) + ".jpg"; ImageIO.write(image, IMAGE_FORMAT, new File(destPath + "/" + file)); } public static void mkdirs(String destPath) { File file = new File(destPath); // 當文件夾不存在時,mkdirs會自動創建多層目錄,區別於mkdir.(mkdir如果父目錄不存在則會拋出異常) if (!file.exists() && !file.isDirectory()) { file.mkdirs(); } } 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 getImageFormat() { return IMAGEFORMAT; } public void setImageFormat(String IMAGEFORMAT) { this.IMAGEFORMAT = IMAGEFORMAT; } public String getCharType() { return CHARTYPE; } public void setCharType(String CHARTYPE) { this.CHARTYPE = CHARTYPE; } public ErrorCorrectionLevel getCorretionLevel() { return corretionLevel; } public void setCorretionLevel(ErrorCorrectionLevel corretionLevel) { this.corretionLevel = corretionLevel; } public Integer getMargin() { return MARGIN; } public void setMargin(Integer MARGIN) { this.MARGIN = MARGIN; } public Map<EncodeHintType, Object> getHits() { return encodeHits; } public void setHits(Map<EncodeHintType, Object> hits) { this.encodeHits = hits; } //main方法測試工具類 public static void main(String[] args) throws Exception { String text = "鯤鵬展翅"; String path2="D:/MyWorkDoc/test.png"; QrcodeUtils qrCode=new QrcodeUtils(300,300); //設置二維碼的邊緣為1 qrCode.setMargin(MARGIN); //輸出到桌面 //String path=System.getProperty("user.home")+File.separator+"Desktop"+File.separator+"test.png"; //創建圖片二維碼 //qrCode.createQrImage(text, path2);//路徑指定到文件名 //QrcodeUtils.encode(text, "d:/MyWorkDoc/kun.jpg", path2, true);//攜帶LOGO生成二維碼 路徑指定文件夾 //QrcodeUtils.encode(text,"",path2,true);//不攜帶LOGO生成二維碼 路徑指定文件夾 //識別圖片二維碼的內容 System.out.println(qrCode.decodeQrImage(new File(path2)));//路徑指定到文件名 } } package com.company.utils; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.OutputStream; import javax.imageio.ImageIO; import com.google.zxing.common.BitMatrix; public class MatrixToImageWriter { private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; private MatrixToImageWriter() { } 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) ? BLACK : WHITE); } } return image; } public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, file)) { throw new IOException("Could not write an image of format " + format + " to " + file); } } public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, stream)) { throw new IOException("Could not write an image of format " + format); } } }
有重復代碼大家自己看一下