public class TestQrcode {
/**
* @introduction 设置颜色值,由于后来的setRGB方法
* @author Guo
*/
private static final int BLACK = 0xff000000;
private static final int WHITE = 0xFFFFFFFF;
public static void main(String[] args) {
TestQrcode test = new TestQrcode();
File file = new File("G://Picture//qrcode.png");
String str = "很好";
try {
test.encode(new String(str.getBytes("UTF-8"), "ISO-8859-1"), file, BarcodeFormat.QR_CODE, 200, 200);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
/**
* @introduction 解析二维码图片的信息
* @author Guo
*/
//test.decode(file);
}
public void encode(String contents, File file, BarcodeFormat format, int width, int height) {
try {
/**
* @introduction BitMatrix是构建二维矩阵位图的类
* @introduction 通过MultiFormatWriter类编码二维码的格式
* @author Guo
*/
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, format, width, height);
writeToFile(bitMatrix, "png", file);
} catch (Exception e) {
e.printStackTrace();
}
}
public void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
/**
* @introduction BufferedImage描述具有可访问图像数据缓冲区的 Image
* @author Guo
*/
BufferedImage image = toBufferedImage(matrix);
/**
* @introduction ImageIO该类包含一些用来查找 ImageReader 和 ImageWriter 以及执行简单编码和解码的静态便捷方法
* @introduction write方法使用支持给定格式的任意 ImageWriter 将一个图像写入 File
* @author Guo
*/
ImageIO.write(image, format, file);
}
public BufferedImage toBufferedImage(BitMatrix bitMatrix) {
/**
* @introduction 拿到位图的基本数据
* @author Guo
*/
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
/**
* @introduction 构造一个类型为预定义图像类型之一的 BufferedImage
* @author Guo
*/
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
/**
* @introduction 设置黑白位点
* @author Guo
*/
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) == true ? BLACK : WHITE);
}
}
return image;
}
public void decode(File file) {
BufferedImage image;
try {
image = ImageIO.read(file);
if(image == null)
System.out.println("Can not find the image!");
else {
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable hints = new Hashtable();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
System.out.println("解析后内容:" + resultStr);
}
} catch (IOException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
}
}
ZXing二维图
最新推荐文章于 2022-04-10 14:17:10 发布