下面列出了怎么用com.google.zxing.client.j2se.MatrixToImageWriter的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 生成二维码并响应到浏览器
*
* @param content
* @param response
*/
public static void createQRCode(String content, HttpServletResponse response) {
int width = 300, height = 300;
String format = "png";
Map<EncodeHintType, Object> hashMap = new HashMap<>();
hashMap.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8);
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hashMap.put(EncodeHintType.MARGIN, 1);
try {
response.setHeader("Cache-control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setHeader("content-type", "image/png");
response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
response.setDateHeader("Expires", 0);
BitMatrix bitMatrix = new MultiFormatWriter()
.encode(content, BarcodeFormat.QR_CODE, width, height, hashMap);
BufferedImage img = MatrixToImageWriter.toBufferedImage(bitMatrix);
ImageIO.write(img, format, response.getOutputStream());
} catch (Exception e) {
log.warn("create QRCode error message:{}", e.getMessage());
}
}
private Image getQRImage() {
if (qrImage == null) {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
int qrWidth = 500;
int qrHeight = 500;
BitMatrix byteMatrix = null;
try {
byteMatrix = qrCodeWriter.encode(getMLURL(), BarcodeFormat.QR_CODE, qrWidth, qrHeight);
} catch (WriterException ex) {
LOGGER.log(Level.WARNING, "Error writing QR code", ex);
}
qrImage = MatrixToImageWriter.toBufferedImage(byteMatrix);
}
WritableImage fxImg = new WritableImage(500, 500);
SwingFXUtils.toFXImage(qrImage, fxImg);
return fxImg;
}
/**
* @param dir 生成二维码路径
* @param content 内容
* @param width 宽度
* @param height 高度
* @return
*/
public static String createQRCodeImage(String dir, String content, int width, int height) {
try {
File dirFile = null;
if (StringUtils.isNotBlank(dir)) {
dirFile = new File(dir);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
}
String qrcodeFormat = "png";
HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
File file = new File(dir, UUID.randomUUID().toString() + "." + qrcodeFormat);
MatrixToImageWriter.writeToPath(bitMatrix, qrcodeFormat, file.toPath());
return file.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static BufferedImage PDF417(String code, int pdf417ErrorCorrectionLevel,
Compaction pdf417Compact,
int pdf417Width, int pdf417Height, int pdf417Margin) {
try {
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, pdf417ErrorCorrectionLevel);
hints.put(EncodeHintType.MARGIN, pdf417Margin);
if (pdf417Compact == null) {
hints.put(EncodeHintType.PDF417_COMPACT, false);
} else {
hints.put(EncodeHintType.PDF417_COMPACT, true);
hints.put(EncodeHintType.PDF417_COMPACTION, pdf417Compact);
}
BitMatrix bitMatrix = new MultiFormatWriter().encode(code,
BarcodeFormat.PDF_417, pdf417Width, pdf417Height, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
} catch (Exception e) {
logger.error(e.toString());
return null;
}
}
public static BufferedImage DataMatrix(String code,
int dmWidth, int dmHeigh) {
try {
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(code,
BarcodeFormat.DATA_MATRIX, dmWidth, dmHeigh, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
} catch (Exception e) {
logger.error(e.toString());
return null;
}
}
/**
* 生成带有logo的二维码
* @param text 生成文本
* @param logoInputStream logo文件输入流
* @param qrCodeWidth 二维码宽度
* @param qrCodeHeight 二维码高度
* @param logoWidth logo宽度
* @param logoHeight logo高度
* @param ENCODE_HINTS 二维码配置
* @return 输出流
* @throws WriterException
* @throws IOException
*/
private static Thumbnails.Builder<BufferedImage> createWidthLogo(String text, InputStream logoInputStream, int qrCodeWidth, int qrCodeHeight, int logoWidth, int logoHeight,
String format, Map<EncodeHintType, Object> ENCODE_HINTS) throws WriterException, IOException {
BitMatrix bitMatrix = createBitMatrix(text, BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeHeight, ENCODE_HINTS);
/* 生成二维码的bufferedImage */
BufferedImage qrcode = MatrixToImageWriter.toBufferedImage(bitMatrix);
/* 创建图片构件对象 */
Thumbnails.Builder<BufferedImage> builder = Thumbnails.of(new BufferedImage(qrCodeWidth, qrCodeHeight, BufferedImage.TYPE_INT_RGB));
BufferedImage logo = ImageIO.read(logoInputStream);
BufferedImage logoImage = Thumbnails.of(logo).size(logoWidth, logoHeight).asBufferedImage();
/* 设置logo水印位置居中,不透明 */
builder.watermark(Positions.CENTER, qrcode, 1F)
.watermark(Positions.CENTER, logoImage, 1F)
.scale(1F)
.outputFormat(format);
return builder;
}
/**
* 将内容contents生成长为width,宽为width的图片,返回刘文静
*/
public static ServletOutputStream getQRCodeImge(String contents, int width, int height) throws IOException {
ServletOutputStream stream = null;
try {
Map<EncodeHintType, Object> hints = Maps.newHashMap();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.CHARACTER_SET, "UTF8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);
return stream;
} catch (Exception e) {
log.error("create QR code error!", e);
return null;
} finally {
if (stream != null) {
stream.close();
}
}
}
/**
* 二维码信息写成JPG BufferedImage
*
* @param content
* @param width
* @param height
* @return
*/
public static BufferedImage writeInfoToJpgBuffImg(String content, int width, int height) {
if (width < 250) {
width = 250;
}
if (height < 250) {
height = 250;
}
BufferedImage re = null;
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
BitMatrix bitMatrix = multiFormatWriter.encode(content,
BarcodeFormat.QR_CODE, width, height, hints);
re = MatrixToImageWriter.toBufferedImage(bitMatrix);
} catch (Exception e) {
e.printStackTrace();
}
return re;
}
/**
* 条形码编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encode(String contents, int width, int height, String imgPath) {
int codeWidth = 3 + // start guard
(7 * 6) + // left bars
5 + // middle guard
(7 * 6) + // right bars
3; // end guard
codeWidth = Math.max(codeWidth, width);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.EAN_13, codeWidth, height, null);
MatrixToImageWriter
.writeToFile(bitMatrix, "png", new File(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 二维码编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encode2(String contents, int width, int height, String imgPath) {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "GBK");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter
.writeToFile(bitMatrix, "png", new File(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}
@ResponseBody
@RequestMapping(method = RequestMethod.GET, value = "/{productId}/ean")
public ResponseEntity<?> getProductEAN(@PathVariable String productId) throws WriterException, IOException {
Product product = repository.findOne(productId);
if (product == null) {
return ResponseEntity.notFound().build();
}
EAN13Writer ean13Writer = new EAN13Writer();
BitMatrix matrix = ean13Writer.encode(product.getEan(), BarcodeFormat.EAN_13, 300, 200);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(matrix);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", baos);
byte[] imageData = baos.toByteArray();
ByteArrayResource byteArrayResource = new ByteArrayResource(imageData);
return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(byteArrayResource);
}
@RequireAnyAuthority
@RequestMapping(value = "/qr", method = RequestMethod.GET)
public void qrcode(HttpServletResponse response,
@AuthenticationPrincipal JpaUserDetails jpaUserDetails)
throws WriterException, IOException {
User user = jpaUserDetails.getUser(this.jpaQueryFactory);
if (user != null && StringUtils.hasText(user.getSecret())) {
response.setContentType("image/png");
String contents = "otpauth://totp/" + user.getEmail() + "?secret="
+ user.getSecret() + "&issuer=" + this.appName;
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = writer.encode(contents, BarcodeFormat.QR_CODE, 200, 200);
MatrixToImageWriter.writeToStream(matrix, "PNG", response.getOutputStream());
response.getOutputStream().flush();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/generate", method = RequestMethod.GET)
@ApiOperation(value="获取二维码图片")
@ApiResponses(value = { @ApiResponse(code = 401, message = "请求未通过认证") })
public void generateQRCode(@RequestParam(value = "content") String content, HttpServletResponse response) {
logger.info("generate QRCode...");
try {
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH_DEFAULT, QRCODE_HEIGHT_DEFAULT, hints);
response.setContentType(CONTENT_TYPE_JPG);
OutputStream stream = response.getOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, QRCODE_FORMATE_DEFAULT, stream);
stream.flush();
stream.close();
} catch (Exception e) {
logger.error("generate QRCode error, {}", e.getMessage());
}
}
private void renderCode(H.Response response) {
response.contentType("image/png");
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, Act.appConfig().encoding());
hints.put(EncodeHintType.MARGIN, 0);
ErrorCorrectionLevel level = errorCorrectionLevel();
if (null != level) {
hints.put(EncodeHintType.ERROR_CORRECTION, level);
}
MultiFormatWriter writer = new MultiFormatWriter();
try {
BitMatrix bitMatrix = writer.encode(getMessage(), barcodeFormat(), width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, "png", response.outputStream());
} catch (Exception e) {
throw E.unexpected(e);
}
}
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);
}
}
@Override
public void draw(Graphics2D g, int x, int y, int width) {
Graphics2D g2d = (Graphics2D) g;
AffineTransform oldt = g2d.getTransform();
g2d.translate(x - 10 + (width - (int) (m_iWidth * scale)) / 2, y + 10);
g2d.scale(scale, scale);
try {
if (m_qrMatrix != null) {
com.google.zxing.Writer writer = new QRCodeWriter();
m_qrMatrix = writer.encode(m_sCode, com.google.zxing.BarcodeFormat.QR_CODE, m_iWidth, m_iHeight);
g2d.drawImage(MatrixToImageWriter.toBufferedImage(m_qrMatrix), null, 0, 0);
} else if (m_barcode != null) {
m_barcode.generateBarcode(new Java2DCanvasProvider(g2d, 0), m_sCode);
}
} catch (IllegalArgumentException | WriterException ex) {
g2d.drawRect(0, 0, m_iWidth, m_iHeight);
g2d.drawLine(0, 0, m_iWidth, m_iHeight);
g2d.drawLine(m_iWidth, 0, 0, m_iHeight);
}
g2d.setTransform(oldt);
}
public static byte[] createQRCodeWithDescription(String text, String description) {
try (InputStream fi = new ClassPathResource("/alfio/font/DejaVuSansMono.ttf").getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
BitMatrix matrix = drawQRCode(text);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(matrix);
BufferedImage scaled = new BufferedImage(200, 230, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = (Graphics2D)scaled.getGraphics();
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.drawImage(bufferedImage, 0,0, null);
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 200, 200, 30);
graphics.setColor(Color.BLACK);
graphics.setFont(Font.createFont(Font.TRUETYPE_FONT, fi).deriveFont(14f));
graphics.drawString(center(truncate(description, 23), 25), 0, 215);
ImageIO.write(scaled, "png", baos);
return baos.toByteArray();
} catch (WriterException | IOException | FontFormatException e) {
throw new IllegalStateException(e);
}
}
public static String qrCode(String totpSecret, RealmModel realm, UserModel user) {
try {
String keyUri = realm.getOTPPolicy().getKeyURI(realm, user, totpSecret);
int width = 246;
int height = 246;
QRCodeWriter writer = new QRCodeWriter();
final BitMatrix bitMatrix = writer.encode(keyUri, BarcodeFormat.QR_CODE, width, height);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "png", bos);
bos.close();
return Base64.encodeBytes(bos.toByteArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public byte[] generate(QrData data) throws QrGenerationException {
try {
BitMatrix bitMatrix = writer.encode(data.getUri(), BarcodeFormat.QR_CODE, imageSize, imageSize);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
return pngOutputStream.toByteArray();
} catch (Exception e) {
throw new QrGenerationException("Failed to generate QR code. See nested exception.", e);
}
}
/**
* 条形码编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encode(String contents, int width, int height, String imgPath) {
int codeWidth = 3 + // start guard
(7 * 6) + // left bars
5 + // middle guard
(7 * 6) + // right bars
3; // end guard
codeWidth = Math.max(codeWidth, width);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.EAN_13, codeWidth, height, null);
MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(imgPath).toPath());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 二维码编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encode2(String contents, int width, int height, String imgPath) {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "GBK");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(imgPath).toPath());
} catch (Exception e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/otp/qrcode/{userid}.png", method = RequestMethod.GET)
public void generateQRCode(HttpServletResponse response, @PathVariable("userid") Long userId) throws WriterException, IOException {
String otpProtocol = userService.generateOTPProtocol(userId);
response.setContentType("image/png");
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = writer.encode(otpProtocol, BarcodeFormat.QR_CODE, 250, 250);
MatrixToImageWriter.writeToStream(matrix, "PNG", response.getOutputStream());
response.getOutputStream().flush();
}
/**
* 创建二维码
*
* @param content 二维码内容
* @param width 宽度
* @param height 高度
* @param margin 二维码边距
* @return BufferedImage 返回图片
* @throws WriterException 异常
*/
public static BufferedImage createQrCode(String content, int width, int height, int margin) throws WriterException {
Map<EncodeHintType, Comparable> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 字符串编码
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 纠错等级
hints.put(EncodeHintType.MARGIN, margin); // 图片边距
QRCodeWriter writer = new QRCodeWriter();
return MatrixToImageWriter.toBufferedImage(writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints));
}
/**
* 生成二维码
*/
@Override
public byte[] createQRCodeImage(String text, int width, int height) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
byte[] pngData = pngOutputStream.toByteArray();
return pngData;
}
public void runPass()
{
try
{
String wallet_name = (String)wallet_select_box.getSelectedItem();
if (wallet_name == null)
{
setMessageBox("no wallet selected");
setStatusBox("");
return;
}
SnowBlossomClient client = ice_leaf.getWalletPanel().getWallet( wallet_name );
if (client == null)
{
setMessageBox("no wallet selected");
setStatusBox("");
return;
}
AddressSpecHash spec = client.getPurse().getUnusedAddress(false,false);
String address_str = spec.toAddressString(ice_leaf.getParams());
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bit_matrix = qrCodeWriter.encode(address_str, BarcodeFormat.QR_CODE, qr_size, qr_size);
BufferedImage bi = MatrixToImageWriter.toBufferedImage(bit_matrix);
setQrImage(bi);
setStatusBox(address_str);
setMessageBox("");
}
catch(Throwable t)
{
setMessageBox(ErrorUtil.getThrowInfo(t));
setStatusBox("");
}
}
public static byte[] getQrImageInBytes(String rawText) throws WriterException, IOException {
int width = 600;
int height = 600;
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(rawText, BarcodeFormat.QR_CODE, width, height, hints);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
return pngOutputStream.toByteArray();
}
/**
* @param content
* @param format
* @param height
* @return
*/
public static File saveBarCode(String content, BarcodeFormat format, int height) {
BitMatrix bitMatrix = createBarCode(content, format, height);
String fileName = String.format("BarCode-%d.png", System.currentTimeMillis());
File dest = SysConfiguration.getFileOfTemp(fileName);
try {
MatrixToImageWriter.writeToPath(bitMatrix, "png", dest.toPath());
return dest;
} catch (IOException ex) {
throw new RebuildException("Write BarCode failed : " + content, ex);
}
}
public static byte[] encode(int width, int height, String content, String format) throws Exception {
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
ByteArrayOutputStream bos = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, format, bos);
return bos.toByteArray();
}
/**
* 生成二维码
*
* @param content 条码文本内容
* @param width 条码宽度
* @param height 条码高度
* @param fileType 文件类型,如png
* @param savePath 保存路径
*/
@SuppressWarnings({"rawtypes", "unchecked", "deprecation"})
public static void encode(String content, int width, int height, String fileType, String savePath) throws IOException, WriterException {
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
byte[] b = encoder.encode(CharBuffer.wrap(content)).array();
String data = new String(b, "iso8859-1");
Writer writer = new QRCodeWriter();
BitMatrix matrix = writer.encode(data, QR_CODE, width, height);
MatrixToImageWriter.writeToPath(matrix, fileType, Paths.get(savePath));
}
/**
* 根据bitMatrix生成二维码
* @param bitMatrix
* @param target
* @param imageType
*/
public static void genCode(BitMatrix bitMatrix, String imageType, String target){
try {
Path path = FileSystems.getDefault().getPath(target);
// 输出图像
MatrixToImageWriter.writeToPath(bitMatrix, imageType, path);
} catch (IOException e) {
e.printStackTrace();
}
}