package com.fuyuanshen.common.core.utils;

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

public class ImageToCArrayConverterUtils {

    public static void main(String[] args) {
        try {
            convertImageToCArray("E:\\workspace\\6170_强光_160_80_2.jpg", "E:\\workspace\\output.c", 160, 80);
            System.out.println("转换成功！");
        } catch (IOException e) {
            System.err.println("转换失败: " + e.getMessage());
        }
    }

    public static void convertImageToCArray(String inputPath, String outputPath,
                                            int width, int height) throws IOException {
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(new File(inputPath));

        // 调整图片尺寸
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        resizedImage.getGraphics().drawImage(
                originalImage, 0, 0, width, height, null);

        // 转换像素数据为RGB565格式（高位在前）
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int rgb = resizedImage.getRGB(x, y);

                // 提取RGB分量
                int r = (rgb >> 16) & 0xFF;
                int g = (rgb >> 8) & 0xFF;
                int b = rgb & 0xFF;

                // 转换为RGB565（5位红，6位绿，5位蓝）
                int r5 = (r >> 3) & 0x1F;
                int g6 = (g >> 2) & 0x3F;
                int b5 = (b >> 3) & 0x1F;

                // 组合为16位值
                int rgb565 = (r5 << 11) | (g6 << 5) | b5;

                // 高位在前（大端序）写入字节
                byteStream.write((rgb565 >> 8) & 0xFF); // 高字节
                byteStream.write(rgb565 & 0xFF);        // 低字节
            }
        }

        byte[] imageData = byteStream.toByteArray();

        // 生成C语言数组文件
        try (FileOutputStream fos = new FileOutputStream(outputPath)) {
            // 写入注释行（包含尺寸信息）
            String header = String.format("/* 0X10,0X10,0X00,0X%02X,0X00,0X%02X,0X01,0X1B, */\n",
                    width, height);
            fos.write(header.getBytes());

            // 写入数组声明
            fos.write("const unsigned char gImage_data[] = {\n".getBytes());

            // 写入数据（每行16个字节）
            for (int i = 0; i < imageData.length; i++) {
                // 写入0X前缀
                fos.write(("0X" + String.format("%02X", imageData[i] & 0xFF)).getBytes());

                // 添加逗号（最后一个除外）
                if (i < imageData.length - 1) {
                    fos.write(',');
                }

                // 换行和缩进
                if ((i + 1) % 16 == 0) {
                    fos.write('\n');
                } else {
                    fos.write(' ');
                }
            }

            // 写入数组结尾
            fos.write("\n};\n".getBytes());
        }
    }
}