Java后台直接生成二维码
1、其实jquery也可以直接生成二维码的,但我测试的时候,二维码生成后太模糊,难以识别。所以在这里介绍在后来生成二维码的方式。
2、不善于文字描述,直接上代码了。
1 import java.awt.Graphics2D; 2 import java.awt.geom.AffineTransform; 3 import java.awt.image.BufferedImage; 4 import java.io.File; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 import java.util.HashMap; 8 import java.util.Hashtable; 9 import java.util.Map; 10 11 import javax.imageio.ImageIO; 12 import javax.servlet.http.HttpServletResponse; 13 14 import org.slf4j.Logger; 15 import org.slf4j.LoggerFactory; 16 17 import com.google.zxing.BarcodeFormat; 18 import com.google.zxing.Binarizer; 19 import com.google.zxing.BinaryBitmap; 20 import com.google.zxing.DecodeHintType; 21 import com.google.zxing.EncodeHintType; 22 import com.google.zxing.LuminanceSource; 23 import com.google.zxing.MultiFormatReader; 24 import com.google.zxing.MultiFormatWriter; 25 import com.google.zxing.Result; 26 import com.google.zxing.common.BitMatrix; 27 import com.google.zxing.common.HybridBinarizer; 28 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; 29 30 /** 31 *Title:QRCodeUtil
32 *Description: 二维码生成工具类
33 * @author Administrator 34 * @version 35 * @since 36 */ 37 public final class QRCodeUtil extends LuminanceSource { 38 39 private static final Logger logger = LoggerFactory.getLogger(QRCodeUtil.class); 40 41 // 二维码颜色 42 private static final int BLACK = 0xFF000000; 43 // 二维码颜色 44 private static final int WHITE = 0xFFFFFFFF; 45 46 private final BufferedImage image; 47 private final int left; 48 private final int top; 49 50 public QRCodeUtil(BufferedImage image) { 51 this(image, 0, 0, image.getWidth(), image.getHeight()); 52 } 53 54 public QRCodeUtil(BufferedImage image, int left, int top, int width, int height) { 55 super(width, height); 56 int sourceWidth = image.getWidth(); 57 int sourceHeight = image.getHeight(); 58 if (left + width > sourceWidth || top + height > sourceHeight) { 59 throw new IllegalArgumentException("Crop rectangle does not fit within image data."); 60 } 61 for (int y = top; y < top + height; y++) { 62 for (int x = left; x < left + width; x++) { 63 if ((image.getRGB(x, y) & 0xFF000000) == 0) { 64 image.setRGB(x, y, 0xFFFFFFFF); // = white 65 } 66 } 67 } 68 this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY); 69 this.image.getGraphics().drawImage(image, 0, 0, null); 70 this.left = left; 71 this.top = top; 72 } 73 74 @Override 75 public byte[] getRow(int y, byte[] row) { 76 if (y < 0 || y >= getHeight()) { 77 throw new IllegalArgumentException("Requested row is outside the image: " + y); 78 } 79 int width = getWidth(); 80 if (row == null || row.length < width) { 81 row = new byte[width]; 82 } 83 image.getRaster().getDataElements(left, top + y, width, 1, row); 84 return row; 85 } 86 87 @Override 88 public byte[] getMatrix() { 89 int width = getWidth(); 90 int height = getHeight(); 91 int area = width * height; 92 byte[] matrix = new byte[area]; 93 image.getRaster().getDataElements(left, top, width, height, matrix); 94 return matrix; 95 } 96 97 @Override 98 public boolean isCropSupported() { 99 return true; 100 } 101 102 @Override 103 public LuminanceSource crop(int left, int top, int width, int height) { 104 return new QRCodeUtil(image, this.left + left, this.top + top, width, height); 105 } 106 107 @Override 108 public boolean isRotateSupported() { 109 return true; 110 } 111 112 @Override 113 public LuminanceSource rotateCounterClockwise() { 114 int sourceWidth = image.getWidth(); 115 int sourceHeight = image.getHeight(); 116 AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth); 117 BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY); 118 Graphics2D g = rotatedImage.createGraphics(); 119 g.drawImage(image, transform, null); 120 g.dispose(); 121 int width = getWidth(); 122 return new QRCodeUtil(rotatedImage, top, sourceWidth - (left + width), getHeight(), width); 123 } 124 125 /** 126 * @param matrix 127 * @return 128 */ 129 private static BufferedImage toBufferedImage(BitMatrix matrix) { 130 int width = matrix.getWidth(); 131 int height = matrix.getHeight(); 132 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 133 for (int x = 0; x < width; x++) { 134 for (int y = 0; y < height; y++) { 135 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); 136 } 137 } 138 return image; 139 } 140 141 /** 142 * 生成二维码图片 143 * 144 * @param matrix 145 * @param format 146 * @param file 147 * @throws IOException 148 */ 149 public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { 150 BufferedImage image = toBufferedImage(matrix); 151 if (!ImageIO.write(image, format, file)) { 152 throw new IOException("Could not write an image of format " + format + " to " + file); 153 } 154 } 155 156 /** 157 * 生成二维码图片流 158 * 159 * @param matrix 160 * @param format 161 * @param stream 162 * @throws IOException 163 */ 164 public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { 165 BufferedImage image = toBufferedImage(matrix); 166 if (!ImageIO.write(image, format, stream)) { 167 throw new IOException("Could not write an image of format " + format); 168 } 169 } 170 171 /** 172 * 根据内容,生成指定宽高、指定格式的二维码图片 173 * 174 * @param text 内容 175 * @param width 宽 176 * @param height 高 177 * @param format 图片格式 178 * @return 生成的二维码图片路径 179 * @throws Exception 180 */ 181 private static String generateQRCode(String text, int width, int height, String format, String pathName) 182 throws Exception { 183 Hashtablehints = new Hashtable (); 184 hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 指定编码格式 185 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);// 指定纠错等级 186 hints.put(EncodeHintType.MARGIN, 1); // 白边大小,取值范围0~4 187 BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints); 188 File outputFile = new File(pathName); 189 writeToFile(bitMatrix, format, outputFile); 190 return pathName; 191 } 192 193 /** 194 * 输出二维码图片流 195 * 196 * @param text 二维码内容 197 * @param width 二维码宽 198 * @param height 二维码高 199 * @param format 图片格式eg: png, jpg, gif 200 * @param response HttpServletResponse 201 * @throws Exception 202 */ 203 public static void generateQRCode(String text, int width, int height, String format, HttpServletResponse response) 204 throws Exception { 205 Hashtable hints = new Hashtable (); 206 hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 指定编码格式 207 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);// 指定纠错等级 208 hints.put(EncodeHintType.MARGIN, 1); // 白边大小,取值范围0~4 209 BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints); 210 writeToStream(bitMatrix, format, response.getOutputStream()); 211 } 212 213 /** 214 * 解析指定路径下的二维码图片 215 * 216 * @param filePath 二维码图片路径 217 * @return 218 */ 219 public static String parseQRCode(String filePath) { 220 String content = ""; 221 try { 222 File file = new File(filePath); 223 BufferedImage image = ImageIO.read(file); 224 LuminanceSource source = new QRCodeUtil(image); 225 Binarizer binarizer = new HybridBinarizer(source); 226 BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); 227 Map hints = new HashMap (); 228 hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); 229 MultiFormatReader formatReader = new MultiFormatReader(); 230 Result result = formatReader.decode(binaryBitmap, hints); 231 232 logger.info("result 为:" + result.toString()); 233 logger.info("resultFormat 为:" + result.getBarcodeFormat()); 234 logger.info("resultText 为:" + result.getText()); 235 // 设置返回值 236 content = result.getText(); 237 } catch (Exception e) { 238 logger.error(e.getMessage()); 239 } 240 return content; 241 } 242 243 public static void main(String[] args) { 244 String text = "hello world!"; // 随机生成验证码 245 System.out.println("随机码: " + text); 246 int width = 100; // 二维码图片的宽 247 int height = 100; // 二维码图片的高 248 String format = "png"; // 二维码图片的格式 249 250 try { 251 // 生成二维码图片,并返回图片路径 252 String pathName = generateQRCode(text, width, height, format, "D:/new.png"); 253 System.out.println("生成二维码的图片路径: " + pathName); 254 255 String content = parseQRCode(pathName); 256 System.out.println("解析出二维码的图片的内容为: " + content); 257 } catch (Exception e) { 258 e.printStackTrace(); 259 } 260 } 261 262 }
3、需要添加的依赖
12 6com.google.zxing 3core 43.3.0 5