下面列出了怎么用com.google.zxing.qrcode.QRCodeWriter的API类实例代码及写法,或者点击链接到github查看源代码。
public static @NonNull Bitmap create(String data) {
try {
BitMatrix result = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, 512, 512);
Bitmap bitmap = Bitmap.createBitmap(result.getWidth(), result.getHeight(), Bitmap.Config.ARGB_8888);
for (int y = 0; y < result.getHeight(); y++) {
for (int x = 0; x < result.getWidth(); x++) {
if (result.get(x, y)) {
bitmap.setPixel(x, y, Color.BLACK);
}
}
}
return bitmap;
} catch (WriterException e) {
Log.w(TAG, e);
return Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888);
}
}
public static Image encode(String data, int width, int height) {
try {
BitMatrix byteMatrix = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, width, height);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bufferedImage.createGraphics();
Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
graphics.setColor(Color.decode("#00adb5"));
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.BLACK);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
return SwingFXUtils.toFXImage(bufferedImage, null);
} catch (WriterException ex) {
ex.printStackTrace();
return null;
}
}
public static Bitmap generateBitmap(String content, int width, int height) {
int margin = 5; //自定义白边边框宽度
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Hashtable hints = new Hashtable<>();
hints.put(EncodeHintType.MARGIN, 0);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
// encode = updateBit(encode, margin); //生成新的bitMatrix
int[] pixels = new int[width * height];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (encode.get(j, i)) {
pixels[i * width + j] = 0x00000000;
} else {
pixels[i * width + j] = 0xffffffff;
}
}
}
return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
private Bitmap createQrCode(final byte[] contents) {
final BitMatrix result;
try {
final QRCodeWriter writer = new QRCodeWriter();
final Map<EncodeHintType,Object> hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.ISO_8859_1);
final int size = Math.min(imageView.getWidth(), imageView.getHeight());
result = writer.encode(new String(contents, StandardCharsets.ISO_8859_1), BarcodeFormat.QR_CODE,
size, size, hints);
} catch (WriterException e) {
throw new RuntimeException(e);
}
final int width = result.getWidth();
final int height = result.getHeight();
final int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
final int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.RGB_565);
}
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;
}
public void showQrImage(String uuid) {
String uid = null != uuid ? uuid : this.uuid;
String url = "https://login.weixin.qq.com/qrcode/" + uid + "?t=webwx";
final File output = new File("temp.jpg");
//下载二维码
File qrImage = HttpClientUtil.doGetImage(url);
//控制台显示二维码
Map<EncodeHintType, Object> hintMap = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hintMap.put(EncodeHintType.MARGIN, 1);
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
String qrContent = readQRCode(qrImage, hintMap);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix;
try {
bitMatrix = qrCodeWriter.encode(qrContent, BarcodeFormat.QR_CODE, 10, 10, hintMap);
System.out.println(toAscii(bitMatrix));
} catch (WriterException e) {
e.printStackTrace();
}
}
public static Bitmap generateBitmap(String content, int width, int height) {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (encode.get(j, i)) {
pixels[i * width + j] = 0x00000000;
} else {
pixels[i * width + j] = 0xffffffff;
}
}
}
return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
/**
* 生成包含字符串信息的二维码图片
*
* @param outputStream 文件输出流路径
* @param content 二维码携带信息
* @param qrCodeSize 二维码图片大小
* @param imageFormat 二维码的格式
* @throws WriterException
* @throws IOException
*/
public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException {
//设置二维码纠错级别MAP
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 矫错级别
QRCodeWriter qrCodeWriter = new QRCodeWriter();
//创建比特矩阵(位矩阵)的QR码编码的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
// 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点)
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth - 200, matrixWidth - 200, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
// 使用比特矩阵画并保存图像
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i - 100, j - 100, 1, 1);
}
}
}
return ImageIO.write(image, imageFormat, outputStream);
}
/**
* 生成带logo的二维码
*
* @param content 条码文本内容
* @param width 条码宽度
* @param height 条码高度
* @param logoPath 条码中logo的路径
* @param fileType 文件类型,如png
* @param savePath 保存路径
*/
public static void encodeLogo(String content, int width, int height, String logoPath, 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);
MatrixToLogoImageConfig logoConfig = new MatrixToLogoImageConfig(Color.BLACK, 10);
MatrixToImageWriterEx.writeToFile(matrix, fileType, savePath, logoPath, logoConfig);
// BitMatrix matrix = MatrixToImageWriterEx.createQRCode(content, width, height);
// MatrixToLogoImageConfig logoConfig = new MatrixToLogoImageConfig(Color.BLUE, 4);
// MatrixToImageWriterEx.writeToFile(matrix, fileType, savePath, logoPath, logoConfig);
}
public Bitmap generate(String text, int width, int height) {
if ((width <= 0) || (height <= 0)) return null;
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
try {
BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (bitMatrix.get(j, i)) {
pixels[i * width + j] = 0x00000000;
} else {
pixels[i * height + j] = 0xffffffff;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
bitmap = addLogo(bitmap);
return bitmap;
} catch (WriterException ex) {
Timber.e(ex);
}
return null;
}
public Bitmap generateQRCode(String text) {
Bitmap bmp = null;
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // H = 30% damage
int size = 256;
BitMatrix bitMatrix = null;
try {
bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, size, size, hintMap);
int width = bitMatrix.getWidth();
bmp = Bitmap.createBitmap(width, width, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < width; y++) {
bmp.setPixel(y, x, bitMatrix.get(x, y) == true ? Color.BLACK : Color.WHITE);
}
}
} catch (WriterException e) {
e.printStackTrace();
}
return bmp;
}
/**
* Generate a QR code containing the given Wi-Fi configuration
*
* @param width the width of the QR code
* @param wifiNetwork the Wi-Fi configuration
* @return a bitmap representing the QR code
* @throws WriterException if the Wi-Fi configuration cannot be represented in the QR code
*/
public static Bitmap generateWifiQrCode(int width, WifiNetwork wifiNetwork) throws WriterException {
int height = width;
com.google.zxing.Writer writer = new QRCodeWriter();
String wifiString = getWifiString(wifiNetwork);
BitMatrix bitMatrix = writer.encode(wifiString, BarcodeFormat.QR_CODE, width, height);
Bitmap imageBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
imageBitmap.setPixel(i, j, bitMatrix.get(i, j) ? Color.BLACK : Color.WHITE);
}
}
return imageBitmap;
}
public static Bitmap encodeToQrCode(String text, int width, int height){
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = null;
try {
matrix = writer.encode(text, BarcodeFormat.QR_CODE, 100, 100);
} catch (WriterException ex) {
ex.printStackTrace();
}
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++){
for (int y = 0; y < height; y++){
bmp.setPixel(x, y, matrix.get(x,y) ? Color.BLACK : Color.WHITE);
}
}
return bmp;
}
public static Bitmap create2dBarcodeBitmap(String input, int size) {
try {
final QRCodeWriter barcodeWriter = new QRCodeWriter();
final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
final BitMatrix result = barcodeWriter.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
final int width = result.getWidth();
final int height = result.getHeight();
final int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
final int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.WHITE;
}
}
final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
@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();
}
}
@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 Bitmap create2dBarcodeBitmap(String input, int size) {
try {
final QRCodeWriter barcodeWriter = new QRCodeWriter();
final Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
final BitMatrix result = barcodeWriter.encode(input, BarcodeFormat.QR_CODE, size, size, hints);
final int width = result.getWidth();
final int height = result.getHeight();
final int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
final int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.WHITE;
}
}
final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
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);
}
}
/**
* 创建二维码
*
* @param content content
* @param widthPix widthPix
* @param heightPix heightPix
* @param logoBm logoBm
* @return 二维码
*/
public static Bitmap createQRCode(String content, int widthPix, int heightPix, Bitmap logoBm) {
try {
if (content == null || "".equals(content)) {
return null;
}
// 配置参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000;
} else {
pixels[y * widthPix + x] = 0xffffffff;
}
}
}
// 生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
if (logoBm != null) {
bitmap = addLogo(bitmap, logoBm);
}
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
/**
* 创建二维码
*
* @param content content
* @param widthPix widthPix
* @param heightPix heightPix
* @param logoBm logoBm
* @return 二维码
*/
public static Bitmap createQRCode(String content, int widthPix, int heightPix, Bitmap logoBm) {
try {
if (content == null || "".equals(content)) {
return null;
}
// 配置参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000;
} else {
pixels[y * widthPix + x] = 0xffffffff;
}
}
}
// 生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
if (logoBm != null) {
bitmap = addLogo(bitmap, logoBm);
}
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
private ByteArrayOutputStream generateQRCodeByteArrayOutputStream(String value, int size) throws QRCodeException {
try {
BitMatrix result = new QRCodeWriter().encode(value, BarcodeFormat.QR_CODE, size, size, null);
Bitmap qrcode = BitMatrixUtils.convertToBitmap(result);
return generateImageByteArrayOutputStream(qrcode);
} catch (IllegalArgumentException | WriterException | IOException e) {
// Unsupported format
throw new QRCodeException("QRCode generation error", e);
}
}
/**
* 创建二维码
*
* @param content content
* @param widthPix widthPix
* @param heightPix heightPix
* @param logoBm logoBm
* @return 二维码
*/
public static Bitmap createQRCode(String content, int widthPix, int heightPix, Bitmap logoBm) {
try {
if (content == null || "".equals(content)) {
return null;
}
// 配置参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 容错级别 这里选择最高H级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 图像数据转换,使用了矩阵转换 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000; // 黑色
} else {
pixels[y * widthPix + x] = 0xffffffff;// 白色
}
}
}
// 生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
if (logoBm != null) {//绘制logo
bitmap = addLogo(bitmap, logoBm);
}
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
/**
* 生成二维码图片
*
* @return
*/
public static Bitmap createBitmap(String text, int QR_WIDTH, int QR_HEIGHT) {
Bitmap bitmap = null;
try {
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix = new QRCodeWriter().encode(text,
BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
for (int y = 0; y < QR_HEIGHT; y++) {
for (int x = 0; x < QR_WIDTH; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * QR_WIDTH + x] = 0xff000000;
} else {
pixels[y * QR_WIDTH + x] = 0xffffffff;
}
}
}
bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
Bitmap.Config.ARGB_4444);
bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
} catch (WriterException e) {
e.printStackTrace();
}
return bitmap;
}
@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 content
* @param widthPix widthPix
* @param heightPix heightPix
* @param logoBm logoBm
* @return 二维码
*/
public static Bitmap createQRCode(String content, int widthPix, int heightPix, Bitmap logoBm) {
try {
if (content == null || "".equals(content)) {
return null;
}
// 配置参数
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000;
} else {
pixels[y * widthPix + x] = 0xffffffff;
}
}
}
// 生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
if (logoBm != null) {
bitmap = addLogo(bitmap, logoBm);
}
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
public void createQRImage(String url) {
int QR_WIDTH = mScreenWidth;
int QR_HEIGHT = mScreenWidth;
try {
//判断URL合法性
if (url == null || "".equals(url) || url.length() < 1) {
return;
}
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
//下面这里按照二维码的算法,逐个生成二维码的图片,
//两个for循环是图片横列扫描的结果
for (int y = 0; y < QR_HEIGHT; y++) {
for (int x = 0; x < QR_WIDTH; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * QR_WIDTH + x] = 0xff000000;
} else {
pixels[y * QR_WIDTH + x] = 0xffffffff;
}
}
}
//生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
//显示到一个ImageView上面
ivQrcode.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
/**
* 创建二维码
*
* @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("");
}
}
/**
* 创建二维码
*
* @param content content
* @param widthPix widthPix
* @param heightPix heightPix
* @param logoBm logoBm
* @return 二维码
*/
public static Bitmap createQRCode(String content, int widthPix, int heightPix, Bitmap logoBm) {
try {
if (content == null || "".equals(content)) {
return null;
}
// 配置参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000;
} else {
pixels[y * widthPix + x] = 0xffffffff;
}
}
}
// 生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
if (logoBm != null) {
bitmap = addLogo(bitmap, logoBm);
}
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}