pom
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
</dependency>
代码
package com.sxapp.img.utils;
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.decoder.ErrorCorrectionLevel;
import com.sanxiang.exception.SXException;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
public class QrCodeUtil {
public static BufferedImage replaceQrCode(BufferedImage originImage, BufferedImage qrImage) throws NotFoundException {
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(originImage)));
Map<DecodeHintType, Object> hints = new HashMap<>(1);
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(binaryBitmap, hints);
ResultPoint[] resultPoint = result.getResultPoints();
float x1 = resultPoint[0].getX();
float y1 = resultPoint[0].getY();
float x2 = resultPoint[1].getX();
float y2 = resultPoint[1].getY();
int deviate = 25;
final int length = (int) Math.sqrt(Math.abs(x1 - x2) * Math.abs(x1 - x2) + Math.abs(y1 - y2) * Math.abs(y1 - y2)) + 2 * deviate;
int x = Math.round(x2) - deviate;
int y = Math.round(y2) - deviate;
Graphics2D graphics = originImage.createGraphics();
graphics.drawImage(qrImage, x, y, length, length, null);
originImage.flush();
graphics.dispose();
return originImage;
}
public static BufferedImage generateQrCodeImage(String content, int width, int height, String format) {
HashMap<EncodeHintType, Object> hints = new HashMap<>(4);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, format, byteArrayOutputStream);
return ImageIO.read(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
} catch (Exception e) {
e.printStackTrace();
throw new SXException();
}
}
}
java二维码定位获取坐标并替换原来二维码