使用Java對Egret的圖集進行拆分

本次使用的是 JDK1.8,並且使用了Json工具包 Jackson

大致代碼如下:

 


/**
 * @author kxvz
 * @title EgretAtlasUtil
 * @description 對Egret圖集進行處理的工具類, 有任何問題可以聯繫郵箱
 * @modify TODO
 * @date 2020/12/18 15:55
 * @mailto [email protected]
 */
public class EgretAtlasUtil {

    /**
     * 把需要處理的圖集內容(json+png)放到某個文件夾下,這裏是設置需要處理的文件夾路徑的
     */
    private static final String DIR_PATH = "/Users/admin/develop/tmp/t1";
    /**
     * 此處是處理好後輸出的圖片的保存文件夾,爲了避免出現文件名衝突,最好新建一個空文件夾進行存放
     */
    private static final String OUT_DIR_PATH = "/Users/admin/develop/tmp/t2";

    /**
     * 入口
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        test();
    }

    /**
     * 開始處理
     *
     * @throws Exception
     */
    public static void test() throws Exception {
        readAndCut(DIR_PATH, OUT_DIR_PATH);
    }

    /**
     * 讀取文件並進行切分
     *
     * @param dirPath
     * @param outDirPath
     * @throws Exception
     */
    private static void readAndCut(String dirPath, String outDirPath) throws Exception {
        /**
         * 得到文件夾下所有文件
         */
        Stream<Path> list = Files.list(Paths.get(dirPath));
        AtomicInteger count = new AtomicInteger(0);
        AtomicInteger succ = new AtomicInteger(0);
        AtomicInteger fail = new AtomicInteger(0);
        /**
         * 過濾出Json文件,只對JSON文件進行處理
         */
        list.filter(tmp -> tmp.getFileName().toString().endsWith(".json")).forEach(tmp -> {
            count.incrementAndGet();
            try {
                cutting(tmp, outDirPath);
                System.out.println(tmp.getFileName() + " 已經處理完成!");
                succ.incrementAndGet();
            } catch (Exception e) {
                System.err.println(tmp.getFileName() + " => " + e.getMessage());
                fail.incrementAndGet();
            }
        });

        /**
         * 輸出統計信息
         */
        System.out.println("一共處理: " + count.get() + " 條數據, 其中成功: " + succ.get() + " 條, 失敗: " + fail.get() + " 條!");
    }

    /**
     * 處理JSON文件
     *
     * @param jsonFile
     * @param outDir
     * @throws Exception
     */
    private static void cutting(Path jsonFile, String outDir) throws Exception {
        if (jsonFile == null) {throw new RuntimeException("Json1文件不存在!");}
        File json = jsonFile.toFile();
        if (!json.exists() || !json.isFile()) {throw new RuntimeException("Json2文件不存在!");}
        List<String> jsonLines = Files.readAllLines(jsonFile);
        if (Checker.isEmpty(jsonLines)) {throw new RuntimeException("Json文件內容爲空!");}

        StringBuilder sb = new StringBuilder();
        for (String s : jsonLines) {
            sb.append(s);
        }

        Path dir = jsonFile.getParent();

        /**
         * JsonUtil 工具使用的是 jackson 工具包: 大致代碼如下
         * ObjectMapper mapper = new ObjectMapper();
         * JsonNode obj =  mapper.readTree(json);
         * 請自行添加相關依賴包
         */
        JsonNode obj = JsonUtil.toObj(sb.toString());

        JsonNode imgNode = obj.get("file");
        /**
         * 如果是普通的圖集信息,這進入此處處理
         */
        if (Checker.isNotEmpty(imgNode)) {
            Path imgPath = Paths.get(dir.toString() + File.separator + imgNode.asText());
            File imgFile = imgPath.toFile();
            if (!imgFile.exists() || !imgFile.isFile()) { throw new RuntimeException("圖片文件不存在!");}
            BufferedImage sourceImage = ImageIO.read(imgFile);

            String imgFileName = imgPath.getFileName().toString();
            String imgName = imgFileName.substring(0, imgFileName.lastIndexOf("."));
            File imgDirFile = new File(outDir + File.separator + imgName);
            if (!imgDirFile.mkdirs()) {throw new RuntimeException("圖片文件夾創建失敗!");}

            JsonNode frames = obj.get("frames");
            Iterator<Map.Entry<String, JsonNode>> fields = frames.fields();
            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> field = fields.next();
                String key = field.getKey();
                JsonNode ele = field.getValue();
                Integer x = ele.get("x").asInt();
                Integer y = ele.get("y").asInt();
                Integer w = ele.get("w").asInt();
                Integer h = ele.get("h").asInt();

                Integer offX = ele.get("offX").asInt();
                Integer offY = ele.get("offY").asInt();
                Integer sourceW = ele.get("sourceW").asInt();
                Integer sourceH = ele.get("sourceH").asInt();

                BufferedImage result = new BufferedImage(sourceW, sourceH, BufferedImage.TYPE_INT_ARGB);
                int[] imageRPG = new int[w * h];
                int[] rgb = sourceImage.getRGB(x, y, w, h, imageRPG, 0, w);
                result.setRGB(offX, offY, w, h, rgb, 0, w);
                ImageIO.write(result, "png", new File(outDir + File.separator + imgName + File.separator + key + ".png"));
            }
            return;
        }

        /**
         * 如果是動畫類的圖集,則進入此處處理
         */
        JsonNode mcNode = obj.get("mc");
        if (Checker.isNotEmpty(mcNode)) {
            JsonNode res = obj.get("res");
            if (Checker.isNotEmpty(res)) {
                String img = null;
                Iterator<Map.Entry<String, JsonNode>> fields = mcNode.fields();
                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> field = fields.next();
                    String key = field.getKey();
                    if (!"res".equalsIgnoreCase(key)) {
                        img = key;
                        break;
                    }
                }

                if (Checker.isEmpty(img)) {
                    throw new RuntimeException("沒找到圖片信息");
                }

                Path imgPath = Paths.get(dir.toString() + File.separator + img + ".png");
                File imgFile = imgPath.toFile();
                if (!imgFile.exists() || !imgFile.isFile()) { throw new RuntimeException("圖片文件不存在!");}
                BufferedImage sourceImage = ImageIO.read(imgFile);

                String imgFileName = imgPath.getFileName().toString();
                String imgName = imgFileName.substring(0, imgFileName.lastIndexOf("."));
                File imgDirFile = new File(outDir + File.separator + imgName);
                if (!imgDirFile.mkdirs()) {throw new RuntimeException("圖片文件夾創建失敗!");}

                Iterator<Map.Entry<String, JsonNode>> ress = res.fields();
                while (ress.hasNext()) {
                    Map.Entry<String, JsonNode> field = ress.next();
                    String key = field.getKey();
                    JsonNode ele = field.getValue();
                    Integer x = ele.get("x").asInt();
                    Integer y = ele.get("y").asInt();
                    Integer w = ele.get("w").asInt();
                    Integer h = ele.get("h").asInt();

                    BufferedImage result = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                    int[] imageRPG = new int[w * h];
                    int[] rgb = sourceImage.getRGB(x, y, w, h, imageRPG, 0, w);
                    result.setRGB(0, 0, w, h, rgb, 0, w);
                    ImageIO.write(result, "png", new File(outDir + File.separator + imgName + File.separator + key + ".png"));
                }
            }
        }
    }
}

 

加了很多註釋,應該都能看懂哈..

最近在學習寫遊戲,有些網上找到的資源不太適合,因此寫了一個這種工具...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章