1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
public class QRCodeUtil {
private final static String CODE = "utf-8"; private final static int WIDTH = 300; private final static int HEIGHT = 300; private final static String FORMAT = "png";
public static<T> void create(OutputStream outputStream, T data) throws Exception{ Map<EncodeHintType, Object> hints = getEncodeHints();
String content = String.valueOf(data);
MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); BitMatrix encode = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
MatrixToImageWriter.writeToStream(encode, FORMAT, outputStream); }
private static Map<EncodeHintType, Object> getEncodeHints() { Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, CODE); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); hints.put(EncodeHintType.MARGIN, 1);
return hints; }
public static<T> T read(InputStream inputStream, Class<T> c) throws Exception{ BufferedImage image = ImageIO.read(inputStream); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
Map<DecodeHintType, Object> hints = getDecodeHints(); MultiFormatReader formatReader = new MultiFormatReader(); Result result = formatReader.decode(binaryBitmap, hints);
return (T) result.getText(); }
private static Map<DecodeHintType, Object> getDecodeHints() { Map<DecodeHintType, Object> hints = new HashMap<>(); hints.put(DecodeHintType.CHARACTER_SET, CODE);
return hints; } }
|