panlili2024
2025-03-05 134209ad70f82051da3ce63471df0cc8f778e57d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.hdl.sdk.sourceos.qrcode;
 
import android.graphics.Bitmap;
import android.text.TextUtils;
 
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * Created by Tong on 2021/11/8.
 * 二维码
 */
public class QRCodeUtils {
 
 
    /**
     * 生成二维码
     */
    public static Bitmap createQRCode(String txt, int width, int height, int margin) throws WriterException {
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        createQRCode(bitmap, txt, width, height, margin);
        return bitmap;
    }
 
 
    /**
     * 生成二维码
     */
    public static void createQRCode(Bitmap bitmap, String txt, int width, int height, int margin) throws WriterException {
 
        if (TextUtils.isEmpty(txt)) {
            return;
        }
 
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        if (margin >= 0) {
            hints.put(EncodeHintType.MARGIN, margin);
        }
 
 
        // 生成二维矩阵
        BitMatrix matrix = new MultiFormatWriter().encode(txt,
                BarcodeFormat.QR_CODE, width, height, hints);
 
        // 二维矩阵转为一维像素数组,也就是一直横着排了
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = 0xff000000;
                } else {
                    pixels[y * width + x] = 0xffffffff;
                }
            }
        }
 
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    }
 
 
}