java 创建二维码和解析二维码

来源:互联网 发布:网络公选课网址 编辑:程序博客网 时间:2024/06/08 18:28
<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator 图片水印 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>



<!-- 二维码创建和解析 -->

<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>

</dependency>


<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>

</dependency>



------------------------------------------

public static void main(String[] args) throws IOException, WriterException, NotFoundException {

BufferedImage watermarkImage = ImageIO.read(new File("d:\\star.png"));
Thumbnails.of("d:\\66.jpg").scale(0.8).watermark(Positions.BOTTOM_LEFT, watermarkImage, 0.5f).toFile("d:\\606.jpg");

//encode("测试中", "d:\\qrcode.png");//解析二维码图片
decode("d:\\123.png");//创建二维码
}



//创建二维码
public static void encode(String content, String filepath) throws WriterException, IOException {
   int width = 300;
   int height = 300;
   Map<EncodeHintType, Object> encodeHints = new HashMap<EncodeHintType, Object>();
   encodeHints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
   BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, encodeHints);
   Path path = FileSystems.getDefault().getPath(filepath);
   MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
}

//解析二维码图片
public static String decode(String filepath) throws IOException, NotFoundException {
   BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
   LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
   Binarizer binarizer = new HybridBinarizer(source);
   BinaryBitmap bitmap = new BinaryBitmap(binarizer);
   HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
   decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
   Result result = new MultiFormatReader().decode(bitmap, decodeHints);
   return result.getText();
}