You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

批量.CGM文件转Base64编码字符串代码实现求助

CGM文件转Base64编码实现代码

不管CGM文件的内容类型,Base64编码是对文件二进制内容的转换,以下是几种常用编程语言的实现代码,支持批量处理:

Python实现

import base64
import os

def cgm_to_base64(file_path):
    with open(file_path, "rb") as f:
        binary_data = f.read()
        return base64.b64encode(binary_data).decode("utf-8")

# 批量处理指定目录下的所有CGM文件
def batch_convert_cgm(folder_path):
    for filename in os.listdir(folder_path):
        if filename.lower().endswith(".cgm"):
            file_path = os.path.join(folder_path, filename)
            base64_str = cgm_to_base64(file_path)
            # 示例:将结果保存为同名txt文件
            with open(f"{file_path}.txt", "w") as out_f:
                out_f.write(base64_str)
            print(f"文件 {filename} 转换完成")

# 使用时替换为你的CGM文件目录路径
batch_convert_cgm("你的CGM文件目录路径")

C#实现

using System;
using System.IO;

class CgmToBase64Converter
{
    static string ConvertCgmToBase64(string filePath)
    {
        byte[] binaryData = File.ReadAllBytes(filePath);
        return Convert.ToBase64String(binaryData);
    }

    static void BatchConvertCgm(string folderPath)
    {
        foreach (string filePath in Directory.GetFiles(folderPath, "*.cgm", SearchOption.TopDirectoryOnly))
        {
            string base64Str = ConvertCgmToBase64(filePath);
            File.WriteAllText($"{filePath}.txt", base64Str);
            Console.WriteLine($"文件 {Path.GetFileName(filePath)} 转换完成");
        }
    }

    static void Main()
    {
        // 使用时替换为你的CGM文件目录路径
        BatchConvertCgm(@"你的CGM文件目录路径");
    }
}

Java实现

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;

public class CgmToBase64 {
    public static String convertCgmToBase64(String filePath) throws IOException {
        byte[] binaryData = Files.readAllBytes(new File(filePath).toPath());
        return Base64.getEncoder().encodeToString(binaryData);
    }

    public static void batchConvertCgm(String folderPath) throws IOException {
        File folder = new File(folderPath);
        File[] files = folder.listFiles((dir, name) -> name.toLowerCase().endsWith(".cgm"));
        if (files != null) {
            for (File file : files) {
                String base64Str = convertCgmToBase64(file.getAbsolutePath());
                Files.write(new File(file.getAbsolutePath() + ".txt").toPath(), base64Str.getBytes());
                System.out.println("文件 " + file.getName() + " 转换完成");
            }
        }
    }

    public static void main(String[] args) throws IOException {
        // 使用时替换为你的CGM文件目录路径
        batchConvertCgm("你的CGM文件目录路径");
    }
}

说明

  • 所有代码均直接读取CGM文件的二进制内容进行编码,无需关注文件具体内容类型
  • 转换后的Base64字符串默认保存为同名txt文件,可根据需求调整输出方式

内容的提问来源于stack exchange,提问作者Sanath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:26:03