package com.fuyuanshen;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class SimpleQR {
    public static void main(String[] args) throws Exception {
        String text = "HELLO";
        int size = 21; // 版本1的大小
        boolean[][] qr = new boolean[size][size];

        // 1. 三个定位标记
        for (int i = 0; i < 7; i++)
            for (int j = 0; j < 7; j++) {
                boolean black = i == 0 || i == 6 || j == 0 || j == 6 || (i > 1 && i < 5 && j > 1 && j < 5);
                qr[i][j] = qr[i][size - 1 - j] = qr[size - 1 - i][j] = black;
            }

        // 2. 定时图案（简化）
        for (int i = 8; i < 13; i++) qr[i][6] = qr[6][i] = (i % 2 == 0);

        // 3. 编码数据（极简编码）
        byte[] data = text.getBytes();
        int x = 20, y = 20, up = 1; // 从右下角开始
        for (byte b : data)
            for (int bit = 7; bit >= 0; bit--) {
                while (qr[x][y] || (x == 6 && y < 9) || (y == 6 && x < 9) || (x < 9 && y < 9) ||
                        (x < 9 && y > size - 10) || (y < 9 && x > size - 10)) {
                    if (up > 0) {
                        if (--y < 0) {
                            y = 0;
                            x -= 2;
                            up = -1;
                        }
                    } else {
                        if (++y >= size) {
                            y = size - 1;
                            x -= 2;
                            up = 1;
                        }
                    }
                    if (x == 6) x--;
                }
                qr[x][y] = ((b >> bit) & 1) == 1;
                if (up > 0) {
                    if (--y < 0) {
                        y = 0;
                        x -= 2;
                        up = -1;
                    }
                } else {
                    if (++y >= size) {
                        y = size - 1;
                        x -= 2;
                        up = 1;
                    }
                }
                if (x == 6) x--;
            }

        // 4. 保存图像
        int scale = 10, margin = 4;
        BufferedImage img = new BufferedImage(
                size * scale + margin * 2, size * scale + margin * 2, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < img.getWidth(); i++)
            for (int j = 0; j < img.getHeight(); j++)
                img.setRGB(i, j, 0xFFFFFF); // 白色背景

        for (int i = 0; i < size; i++)
            for (int j = 0; j < size; j++)
                if (qr[i][j])
                    for (int di = 0; di < scale; di++)
                        for (int dj = 0; dj < scale; dj++)
                            img.setRGB(margin + i * scale + di, margin + j * scale + dj, 0x000000);

        ImageIO.write(img, "PNG", new File("qr.png"));
        System.out.println("二维码已生成");
    }

}