目录
ZXING 生成和读取二维码
package com.example.java11boot.im;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class Ttest2 {
public static void main(String[] args) {
}
public static void make() throws Exception {
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, "1");// 外边距
int width = 200;
int height = 200;
String content = "Hello World By 中国";
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
Path path = Paths.get("D:/hello.PNG");
MatrixToImageWriter.writeToPath(bitMatrix,"PNG", path);
}
public static void read () throws Exception {
QRCodeReader qrCodeReader = new QRCodeReader();
BufferedImage bufferedImage = ImageIO.read(new File("D:/hello.PNG"));
LuminanceSource luminanceSource = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));
Map<DecodeHintType, String> hints2 = new HashMap<>();
hints2.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = qrCodeReader.decode(binaryBitmap, hints2);
System.out.println(result.getText());
}
}
=========================================================================================
@GetMapping("/")
public void qr(HttpServletResponse httpServletResponse) throws Exception {
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, "1");// 外边距
int width = 200;
int height = 200;
String content = "Hello World By 中国";
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
ServletOutputStream outputStream = httpServletResponse.getOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix,"PNG", outputStream);
outputStream.flush();
outputStream.close();
}
=========================================================================================
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
package com.example.demo2;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import org.apache.commons.lang3.RandomStringUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class QRUtil {
/**
* 生成二维码
*
* @param content 二维码内容
* @param width 长度
* @param height 高度
* @param filePath 保留图片的文件夹路径
* @return 二维码的文件名(绝对路径)
* @throws Exception
*/
public static String generator(String content, Integer width, Integer height, String filePath) throws Exception {
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, "1");// 外边距
width = height == null ? 200 : width;
height = height == null ? 200 : height;
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
String fp = filePath + File.separator + RandomStringUtils.randomAlphabetic(8) + ".PNG";
Path path = Paths.get(fp);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
return fp;
}
/**
* 读取二维码
*
* @param file 文件路径
* @return 二维码内容
* @throws Exception
*/
public static String read(File file) throws Exception {
QRCodeReader qrCodeReader = new QRCodeReader();
BufferedImage bufferedImage = ImageIO.read(file);
LuminanceSource luminanceSource = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));
Map<DecodeHintType, String> hints2 = new HashMap<>();
hints2.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = qrCodeReader.decode(binaryBitmap, hints2);
return result.getText();
}
/**
* 读取二维码
*
* @param url 文件路径
* @return 二维码内容
* @throws Exception
*/
public static String read(URL url) throws Exception {
QRCodeReader qrCodeReader = new QRCodeReader();
BufferedImage bufferedImage = ImageIO.read(url);
LuminanceSource luminanceSource = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));
Map<DecodeHintType, String> hints2 = new HashMap<>();
hints2.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = qrCodeReader.decode(binaryBitmap, hints2);
return result.getText();
}
}
=============================带图========================
package com.example.springbootdemo;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class QrCode {
private final String DIR = "D:/z/";
private final String ext = ".png";
private final String LOGO = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
private final String CONTENT = "some content here";
private final int WIDTH = 300;
private final int HEIGHT = 300;
public void generate() {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, "0");// 外边距
QRCodeWriter writer = new QRCodeWriter();
BitMatrix bitMatrix = null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
bitMatrix = writer.encode(CONTENT, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
// Load QR image
BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
// Load logo image
BufferedImage bufferedImage = ImageIO.read(new File("D:/1.png"));
Image image = bufferedImage.getScaledInstance(75, 75, Image.SCALE_SMOOTH);
BufferedImage overly =
new BufferedImage(75, 75, BufferedImage.TYPE_INT_RGB);
Graphics graphics = overly.getGraphics();
graphics.drawImage(image, 0, 0, null);
graphics.dispose();
// Calculate the delta height and width between QR code and logo
int deltaHeight = qrImage.getHeight() - overly.getHeight();
int deltaWidth = qrImage.getWidth() - overly.getWidth();
// Initialize combined image
BufferedImage combined = new BufferedImage(qrImage.getHeight(), qrImage.getWidth(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) combined.getGraphics();
// Write QR code to new image at position 0/0
g.drawImage(qrImage, 0, 0, null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
// Write logo into combine image at position (deltaWidth / 2) and
// (deltaHeight / 2). Background: Left/Right and Top/Bottom must be
// the same space for the logo to be centered
g.drawImage(overly, (int) Math.round(deltaWidth / 2), (int) Math.round(deltaHeight / 2), null);
// Write combined image as PNG to OutputStream
ImageIO.write(combined, "png", os);
// Store Image
Files.copy( new ByteArrayInputStream(os.toByteArray()), Paths.get("D:/z/123." +ext), StandardCopyOption.REPLACE_EXISTING);
} catch (WriterException e) {
e.printStackTrace();
//LOG.error("WriterException occured", e);
} catch (IOException e) {
e.printStackTrace();
//LOG.error("IOException occured", e);
}
}
private BufferedImage getOverly(String LOGO) throws IOException {
File file = new File("D:/1.png");
Image logo = ImageIO.read(new File("D:/1.png"));
Image image = logo.getScaledInstance(80, 80, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(80, 80, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
return ImageIO.read(file);
}
private String generateRandoTitle(Random random, int length) {
return random.ints(48, 122)
.filter(i -> (i < 57 || i > 65) && (i < 90 || i > 97))
.mapToObj(i -> (char) i)
.limit(length)
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
}
public static void main(String[] args) {
QrCode qrCode = new QrCode();
qrCode.generate();
}
}