1. 程式人生 > 實用技巧 >zxing生成和解析二維碼工具類

zxing生成和解析二維碼工具類

1.依賴

        <!--QRCode-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.1.0</version>
        </dependency>

2.工具類

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.
extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.util.HashMap; import java.util.Hashtable; import java.util.UUID; @Component @Slf4j
public class QRCodeUtil { private static final String CHARSET = "utf-8"; private static final String FORMAT_NAME = "jpg"; // 二維碼尺寸 private static final int QRCODE_SIZE = 300; // 二維碼儲存地址 private static String path; public static String getPath() { return path; } @Value(
"${file.linux.path}") public void setPath(String path) { QRCodeUtil.path = path; } /** * 生成二維碼 * @param content * @return * @throws Exception */ public static String createImage(String content) throws Exception { Hashtable<EncodeHintType, Object> hints = new Hashtable<>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints); int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } File files = new File(path); log.debug("資料夾{}",files); if (!files.exists()) {//目錄不存在就建立 files.mkdirs(); } String newName = UUID.randomUUID().toString(); ImageIO.write(image, FORMAT_NAME, new File(files + File.separator + newName + "." + FORMAT_NAME)); return path + newName + "." + FORMAT_NAME; } public static String readImage(MultipartFile file) throws Exception { MultiFormatReader formatReader = new MultiFormatReader(); BufferedImage image = ImageIO.read(file.getInputStream()); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image))); HashMap hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.MARGIN, 1); Result result = formatReader.decode(binaryBitmap,hints); return result.getText(); } }