本文主要是介绍定位并替换原图中的二维码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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;/*** @author Dirk* @Description 二维码* @Date Create at 2019-06-28 16:01*/
public class QrCodeUtil {/*** 替换原图片里面的二维码** @param originImage 原图* @param qrImage 要替换的二维码* @return 替换后的图片* @throws NotFoundException 识别二维码失败*/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;}/*** 生成二维码图片** @param content 内容* @param width 宽度* @param height 高度* @param format 格式* @return 图像*/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二维码定位获取坐标并替换原来二维码
这篇关于定位并替换原图中的二维码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!