下面列出了怎么用com.google.zxing.Writer的API类实例代码及写法,或者点击链接到github查看源代码。
private void doWrite(OutputStream os, Path path) throws IOException {
try {
Writer writer = new MultiFormatWriter();
Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
hints.put(EncodeHintType.MARGIN, Integer.valueOf(margin));
hints.put(EncodeHintType.ERROR_CORRECTION, com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.forBits(errorCorrectionLevel.getBits()));
BitMatrix matrix = writer.encode(uri.toUriString(), BarcodeFormat.QR_CODE, width, height, hints);
if (os != null) {
MatrixToImageWriter.writeToStream(matrix, imageFormatName, os);
}
else {
MatrixToImageWriter.writeToPath(matrix, imageFormatName, path);
}
} catch (WriterException e) {
throw new IOException(e);
}
}
@Test
public void testExceptionIsWrapped() throws WriterException {
Throwable exception = new RuntimeException();
Writer writer = mock(Writer.class);
when(writer.encode(anyString(), any(), anyInt(), anyInt())).thenThrow(exception);
ZxingPngQrGenerator generator = new ZxingPngQrGenerator(writer);
QrGenerationException e = assertThrows(QrGenerationException.class, () -> {
generator.generate(getData());
});
assertEquals("Failed to generate QR code. See nested exception.", e.getMessage());
assertEquals(exception, e.getCause());
}
public ZxingPngQrGenerator(Writer writer) {
this.writer = writer;
}