1、jar包: ZXing-core-3.3.0.jar http://mvnrepository.com/artifact/com.google.zxing/core
ZXing-javase-3.3.0.jar http://mvnrepository.com/artifact/com.google.zxing/javase
BufferedImageLuminanceSource.java
1 package com.webos.util; 2 import java.awt.Graphics2D; 3 import java.awt.geom.AffineTransform; 4 import java.awt.image.BufferedImage; 5 6 import com.google.zxing.LuminanceSource; 7 8 public class BufferedImageLuminanceSource extends LuminanceSource { 9 private final BufferedImage image; 10 private final int left; 11 private final int top; 12 13 public BufferedImageLuminanceSource(BufferedImage image) { 14 this(image, 0, 0, image.getWidth(), image.getHeight()); 15 } 16 17 public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) { 18 super(width, height); 19 20 int sourceWidth = image.getWidth(); 21 int sourceHeight = image.getHeight(); 22 if (left + width > sourceWidth || top + height > sourceHeight) { 23 throw new IllegalArgumentException("Crop rectangle does not fit within image data."); 24 } 25 26 for (int y = top; y < top + height; y++) { 27 for (int x = left; x < left + width; x++) { 28 if ((image.getRGB(x, y) & 0xFF000000) == 0) { 29 image.setRGB(x, y, 0xFFFFFFFF); // = white 30 } 31 } 32 } 33 34 this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY); 35 this.image.getGraphics().drawImage(image, 0, 0, null); 36 this.left = left; 37 this.top = top; 38 } 39 40 public byte[] getRow(int y, byte[] row) { 41 if (y < 0 || y >= getHeight()) { 42 throw new IllegalArgumentException("Requested row is outside the image: " + y); 43 } 44 int width = getWidth(); 45 if (row == null || row.length < width) { 46 row = new byte[width]; 47 } 48 image.getRaster().getDataElements(left, top + y, width, 1, row); 49 return row; 50 } 51 52 public byte[] getMatrix() { 53 int width = getWidth(); 54 int height = getHeight(); 55 int area = width * height; 56 byte[] matrix = new byte[area]; 57 image.getRaster().getDataElements(left, top, width, height, matrix); 58 return matrix; 59 } 60 61 public boolean isCropSupported() { 62 return true; 63 } 64 65 public LuminanceSource crop(int left, int top, int width, int height) { 66 return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height); 67 } 68 69 public boolean isRotateSupported() { 70 return true; 71 } 72 73 public LuminanceSource rotateCounterClockwise() { 74 int sourceWidth = image.getWidth(); 75 int sourceHeight = image.getHeight(); 76 AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth); 77 BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY); 78 Graphics2D g = rotatedImage.createGraphics(); 79 g.drawImage(image, transform, null); 80 g.dispose(); 81 int width = getWidth(); 82 return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width); 83 } 84 }
QRCodeUtil.java
1 package com.webos.util; 2 3 import java.awt.BasicStroke; 4 import java.awt.Graphics; 5 import java.awt.Graphics2D; 6 import java.awt.Image; 7 import java.awt.Shape; 8 import java.awt.geom.RoundRectangle2D; 9 import java.awt.image.BufferedImage; 10 import java.io.File; 11 import java.io.OutputStream; 12 import java.util.Hashtable; 13 import java.util.Random; 14 15 import javax.imageio.ImageIO; 16 17 import com.google.zxing.BarcodeFormat; 18 import com.google.zxing.BinaryBitmap; 19 import com.google.zxing.DecodeHintType; 20 import com.google.zxing.EncodeHintType; 21 import com.google.zxing.MultiFormatReader; 22 import com.google.zxing.MultiFormatWriter; 23 import com.google.zxing.common.BitMatrix; 24 import com.google.zxing.common.HybridBinarizer; 25 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; 26 27 /** 28 * @ClassName: QRCodeUtil 29 * @Description: 二維碼編碼 30 * @author Liuy 31 * @date 2016年7月9日 下午3:03:24 32 * 33 */ 34 public class QRCodeUtil { 35 // 設置二維碼編碼格式 36 private static final String CHARSET = "utf-8"; 37 // 保存的二維碼格式 38 private static final String FORMAT_NAME = "JPG"; 39 // 二維碼尺寸 40 private static final int QRCODE_SIZE = 800; 41 // LOGO寬度 42 private static final int LOGO_WIDTH = 80; 43 // LOGO高度 44 private static final int LOGO_HEIGHT = 80; 45 46 /** 47 * @Title: createImage 48 * @Description: 將二維碼內容創建到Image流 49 * @param content 二維碼內容 50 * @param imgPath logo圖片地址 51 * @param needCompress 是否壓縮logo圖片大小 52 * @return 53 * @throws Exception 參數說明 54 * @return BufferedImage 返回類型 55 * @throws 56 */ 57 private static BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception { 58 Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); 59 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); 60 hints.put(EncodeHintType.CHARACTER_SET, CHARSET); 61 hints.put(EncodeHintType.MARGIN, 1); 62 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints); 63 int width = bitMatrix.getWidth(); 64 int height = bitMatrix.getHeight(); 65 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 66 for (int x = 0; x < width; x++) { 67 for (int y = 0; y < height; y++) { 68 image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); 69 } 70 } 71 if (logoPath == null || "".equals(logoPath)) { 72 return image; 73 } 74 // 插入logo 75 QRCodeUtil.insertImage(image, logoPath, needCompress); 76 return image; 77 } 78 79 /** 80 * @Title: insertImage 81 * @Description: 將logo插入到二維碼中 82 * @param source 二維碼Image流 83 * @param imgPath logo地址 84 * @param needCompress 是否壓縮大小 85 * @throws Exception 參數說明 86 * @return void 返回類型 87 * @throws 88 */ 89 private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception { 90 File file = new File(logoPath); 91 if (!file.exists()) { 92 System.err.println("" + logoPath + " 該文件不存在!"); 93 return; 94 } 95 Image src = ImageIO.read(new File(logoPath)); 96 int width = src.getWidth(null); 97 int height = src.getHeight(null); 98 if (needCompress) { // 壓縮LOGO 99 if (width > LOGO_WIDTH) { 100 width = LOGO_WIDTH; 101 } 102 if (height > LOGO_HEIGHT) { 103 height = LOGO_HEIGHT; 104 } 105 Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH); 106 BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 107 Graphics g = tag.getGraphics(); 108 g.drawImage(image, 0, 0, null); // 繪制縮小後的圖 109 g.dispose(); 110 src = image; 111 } 112 // 插入LOGO 113 Graphics2D graph = source.createGraphics(); 114 int x = (QRCODE_SIZE - width) / 2; 115 int y = (QRCODE_SIZE - height) / 2; 116 graph.drawImage(src, x, y, width, height, null); 117 Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6); 118 graph.setStroke(new BasicStroke(3f)); 119 graph.draw(shape); 120 graph.dispose(); 121 } 122 123 /** 124 * @Title: mkdirs 125 * @Description: 創建文件夾 126 * @param destPath 文件夾地址 127 * @return void 返回類型 128 * @throws 129 */ 130 private static boolean mkdirs(String destPath) { 131 File file = new File(destPath); 132 // 當文件夾不存在時,mkdirs會自動創建多層目錄,區別於mkdir.(mkdir如果父目錄不存在則會拋出異常) 133 if (!file.exists() && !file.isDirectory()) { 134 file.mkdirs(); 135 return true; 136 } 137 138 return false; 139 } 140 141 /** 142 * @Title: encode 143 * @Description: 生成二維碼 144 * @param content 二維碼內容 145 * @param imgPath logo圖片地址 146 * @param destPath 目標保存地址 147 * @param needCompress 是否壓縮logo圖片大小 148 * @throws Exception 參數說明 149 * @return void 返回類型 150 * @throws 151 */ 152 private static void encode(String content, String logoPath, String destPath, boolean needCompress) throws Exception { 153 BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress); 154 if (mkdirs(destPath)) { 155 String file = new Random().nextInt(99999999) + ".jpg"; 156 ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file)); 157 } 158 } 159 160 /** 161 * @Title: encode 162 * @Description: 生成二維碼 163 * @param content 二維碼內容 164 * @param destPath 目標保存地址 165 * @throws Exception 參數說明 166 * @return void 返回類型 167 * @throws 168 */ 169 public static void encode(String content, String destPath) throws Exception { 170 QRCodeUtil.encode(content, null, destPath, false); 171 } 172 173 /** 174 * @Title: encode 175 * @Description: 生成二維碼 176 * @param content 二維碼內容 177 * @param imgPath logo圖片地址 178 * @param output 輸出流 179 * @param needCompress 是否壓縮logo圖片大小 180 * @throws Exception 參數說明 181 * @return void 返回類型 182 * @throws 183 */ 184 public static void encode(String content, String logoPath, OutputStream output, boolean needCompress) throws Exception { 185 BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress); 186 ImageIO.write(image, FORMAT_NAME, output); 187 } 188 189 /** 190 * @Title: encode 191 * @Description: 生成二維碼 192 * @param content 二維碼內容 193 * @param output 輸出流 194 * @throws Exception 參數說明 195 * @return void 返回類型 196 * @throws 197 */ 198 public static void encode(String content, OutputStream output) throws Exception { 199 QRCodeUtil.encode(content, null, output, false); 200 } 201 202 /** 203 * @Title: decode 204 * @Description: 對二維碼解碼 205 * @param file 文件對象 206 * @return 解碼後的二維碼內容字符串 207 * @throws Exception 參數說明 208 * @return String 返回類型 209 * @throws 210 */ 211 private static String decode(File file) throws Exception { 212 BufferedImage image; 213 image = ImageIO.read(file); 214 if (image == null) { 215 return null; 216 } 217 BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image); 218 BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); 219 Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>(); 220 hints.put(DecodeHintType.CHARACTER_SET, CHARSET); 221 return new MultiFormatReader().decode(bitmap, hints).getText(); 222 } 223 224 /** 225 * @Title: decode 226 * @Description: 對二維碼解碼 227 * @param path 文件路徑 228 * @return 229 * @throws Exception 參數說明 230 * @return String 返回類型 231 * @throws 232 */ 233 public static String decode(String path) throws Exception { 234 return QRCodeUtil.decode(new File(path)); 235 } 236 }
QRCodeServlet.java
1 package com.webos.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 import com.webos.util.QRCodeUtil; 12 13 14 /* 15 * Servlet implementation class QRCodeServlet 16 */ 17 @WebServlet("/QRCodeServlet") 18 public class QRCodeServlet extends HttpServlet { 19 private static final long serialVersionUID = 1L; 20 21 /* 22 * @see HttpServlet#HttpServlet() 23 */ 24 public QRCodeServlet() { 25 super(); 26 } 27 28 /* 29 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 30 * response) 31 */ 32 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 33 try { 34 String text = "http://www.baidu.com?timestamp=" + System.currentTimeMillis(); 35 QRCodeUtil.encode(text, response.getOutputStream()); 36 } catch (Exception e) { 37 e.printStackTrace(); 38 } 39 } 40 41 /* 42 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 43 * response) 44 */ 45 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 46 // TODO Auto-generated method stub 47 doGet(request, response); 48 } 49 50 }