use of com.google.zxing.client.j2se.MatrixToImageConfig in project DevKits by qmjy.
the class DKSystemUtil method generateQrImg.
/**
* 生成二维码
*
* @param text 二维码内容
* @param width 二维码图片宽度
* @param height 二维码图片高度
* @return 二维码图片缓冲流
*/
public static BufferedImage generateQrImg(String text, int width, int height) {
HashMap hashMap = new HashMap();
// 设置二维码字符编码
hashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 设置二维码纠错等级
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
// 设置二维码边距
hashMap.put(EncodeHintType.MARGIN, 2);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hashMap);
MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix, matrixToImageConfig);
return bufferedImage;
} catch (WriterException e) {
LOGGER.error("Generate QR file failed...");
}
return null;
}
use of com.google.zxing.client.j2se.MatrixToImageConfig in project i2pplus by I2PPlus.
the class QRServlet method doGet.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getCharacterEncoding() == null)
request.setCharacterEncoding("UTF-8");
String codeParam = request.getParameter(PARAM_IDENTICON_CODE_SHORT);
boolean codeSpecified = codeParam != null && codeParam.length() > 0;
if (!codeSpecified) {
response.setStatus(403);
return;
}
String sizeParam = request.getParameter(PARAM_IDENTICON_SIZE_SHORT);
// very rougly, number of "modules" is about 4 * sqrt(chars)
// (assuming 7 bit) default margin each side is 4
// assuming level L
// min modules is 21x21
// shoot for 2 pixels per module
int size = Math.max(50, (2 * 4) + (int) (2 * 5 * Math.sqrt(codeParam.length())));
if (sizeParam != null) {
try {
size = Integer.parseInt(sizeParam);
if (size < 40)
size = 40;
else if (size > 1024)
size = 1024;
} catch (NumberFormatException nfe) {
}
}
String identiconETag = IdenticonUtil.getIdenticonETag(codeParam.hashCode(), size, version);
String requestETag = request.getHeader("If-None-Match");
if (requestETag != null && requestETag.equals(identiconETag)) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
} else {
byte[] imageBytes = null;
// retrieve image bytes from either cache or renderer
if (cache == null || (imageBytes = cache.get(identiconETag)) == null) {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
QRCodeWriter qrcw = new QRCodeWriter();
BitMatrix matrix;
try {
matrix = qrcw.encode(codeParam, BarcodeFormat.QR_CODE, size, size);
} catch (WriterException we) {
throw new IOException("encode failed", we);
}
String text = request.getParameter(PARAM_IDENTICON_TEXT_SHORT);
if (text != null) {
// add 1 so it generates RGB instead of 1 bit,
// so text anti-aliasing works
MatrixToImageConfig cfg = new MatrixToImageConfig(MatrixToImageConfig.BLACK + 1, MatrixToImageConfig.WHITE);
BufferedImage bi = MatrixToImageWriter.toBufferedImage(matrix, cfg);
Graphics2D g = bi.createGraphics();
// anti-aliasing and hinting for the text
// g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
// g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
// g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
// g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
// scale font
int width = bi.getWidth();
int height = bi.getHeight();
float shrink = Math.min(1.0f, 14.0f / text.length());
if (width >= 256)
shrink = Math.min(1.0f, 16.0f / text.length());
int pts = Math.round(shrink * 16.0f * size / 160);
if (width >= 256)
pts = Math.round(shrink * 16.0f * size / 180);
Font font = new Font(DEFAULT_FONT_NAME, Font.BOLD, pts);
g.setFont(font);
Color color = Color.BLACK;
g.setColor(color);
double swidth = font.getStringBounds(text, 0, text.length(), g.getFontRenderContext()).getBounds().getWidth();
int x = (width - (int) swidth) / 2;
int y = height - 10;
if (height >= 256)
y = height - ((height / 50) + 10);
g.drawString(text, x, y);
if (!ImageIO.write(bi, IDENTICON_IMAGE_FORMAT, byteOut))
throw new IOException("ImageIO.write() fail");
} else {
MatrixToImageWriter.writeToStream(matrix, IDENTICON_IMAGE_FORMAT, byteOut);
}
imageBytes = byteOut.toByteArray();
if (cache != null)
cache.add(identiconETag, imageBytes);
} else {
response.setStatus(403);
return;
}
// set ETag and, if code was provided, Expires header
response.setHeader("ETag", identiconETag);
if (codeSpecified) {
long expires = System.currentTimeMillis() + identiconExpiresInMillis;
response.addDateHeader("Expires", expires);
}
// return image bytes to requester
response.setContentType(IDENTICON_IMAGE_MIMETYPE);
response.setHeader("X-Content-Type-Options", "nosniff");
response.setHeader("Accept-Ranges", "none");
response.setHeader("Cache-control", "max-age=2628000, immutable");
response.setContentLength(imageBytes.length);
response.getOutputStream().write(imageBytes);
}
}
use of com.google.zxing.client.j2se.MatrixToImageConfig in project sparrow by sparrowwallet.
the class QRDisplayDialog method getQrCode.
private Image getQrCode(String fragment) {
try {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix qrMatrix = qrCodeWriter.encode(fragment, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(qrMatrix, "PNG", baos, new MatrixToImageConfig());
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return new Image(bais);
} catch (Exception e) {
log.error("Error generating QR", e);
}
return null;
}
use of com.google.zxing.client.j2se.MatrixToImageConfig in project lilishop by lilishop.
the class QrCodeKit method encode.
/**
* 图形码生成工具
*
* @param contents 内容
* @param barcodeFormat BarcodeFormat对象
* @param format 图片格式,可选[png,jpg,bmp]
* @param width 宽
* @param height 高
* @param margin 边框间距px
* @param saveImgFilePath 存储图片的完整位置,包含文件名
* @return {boolean}
*/
public static boolean encode(String contents, BarcodeFormat barcodeFormat, Integer margin, ErrorCorrectionLevel errorLevel, String format, int width, int height, String saveImgFilePath) {
boolean bool = false;
BufferedImage bufImg;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(3);
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
hints.put(EncodeHintType.MARGIN, margin);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, barcodeFormat, width, height, hints);
MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
bufImg = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
bool = writeToFile(bufImg, format, saveImgFilePath);
} catch (Exception e) {
log.error("图形码生成工具生成错误", e);
}
return bool;
}
use of com.google.zxing.client.j2se.MatrixToImageConfig in project protools by SeanDragon.
the class MatrixToImageWriterEx method writeToFile.
/**
* 写入二维码、以及将照片logo写入二维码中
*
* @param matrix 要写入的二维码
* @param format 二维码照片格式
* @param imagePath 二维码照片保存路径
* @param logoPath logo路径
* @throws IOException
*/
public static void writeToFile(BitMatrix matrix, String format, String imagePath, String logoPath) throws IOException {
MatrixToImageWriter.writeToPath(matrix, format, Paths.get(imagePath), new MatrixToImageConfig());
// 添加logo图片, 此处一定需要重新进行读取,而不能直接使用二维码的BufferedImage 对象
BufferedImage img = ImageIO.read(new File(imagePath));
MatrixToImageWriterEx.overlapImage(img, format, imagePath, logoPath, DEFAULT_CONFIG);
}
Aggregations