java实现将图片转Base64字符,Base64转图片

图片转base64

import java.io.*;
import java.util.Base64;

public class ImageToBase64Converter {

    public static void main(String[] args) {
        String imagePath = "path/to/your/image.png"; // 替换为你的图片路径
        String outputFilePath = "out.txt";

        try {
            File imageFile = new File(imagePath);
            FileInputStream fis = new FileInputStream(imageFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }

            byte[] imageBytes = bos.toByteArray();
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);

            BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath));
            writer.write(base64Image);
            writer.close();

            System.out.println("Base64 representation of the image has been written to out.txt.");

            fis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

base64转图片

import java.io.*;
import java.util.Base64;

public class Base64ToImageConverter {

    public static void main(String[] args) {
        String inputFilePath = "out.txt";
        String outputImagePath = "output.png";

        try {
            BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
            StringBuilder base64Image = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                base64Image.append(line);
            }

            byte[] imageBytes = Base64.getDecoder().decode(base64Image.toString());

            FileOutputStream fos = new FileOutputStream(outputImagePath);
            fos.write(imageBytes);
            fos.close();

            System.out.println("Image has been successfully written to output.png.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

扩展需求:批量操作

批量操作。将 E:\资料\gw-资料 路径下的所有png格式图片,转成base64 ,输出到E:\资料\gw-资料\out.txt 。保留原文件名称的情况下,再将out.txt里面的base64 还原成多个png图片

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class BatchImageToBase64Converter {

    public static void main(String[] args) {
        String inputFolderPath = "E:\\资料\\gw-资料";
        String outputFilePath = "E:\\资料\\gw-资料\\out.txt";

        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFilePath), "UTF-8"));

            Files.walk(Paths.get(inputFolderPath))
                    .filter(Files::isRegularFile)
                    .filter(path -> path.toString().toLowerCase().endsWith(".png"))
                    .forEach(path -> {
                        try {
                            byte[] imageBytes = Files.readAllBytes(path);
                            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
                            writer.write("File: " + path.getFileName() + "\n");
                            writer.write(base64Image + "\n");
                            writer.write("----------\n");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });

            writer.close();
            System.out.println("Base64 representations of images have been written to out.txt.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

还原:

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class BatchBase64ToImageConverter {

    public static void main(String[] args) {
        String inputFilePath = "E:\\资料\\gw-资料\\out.txt";
        String outputFolderPath = "E:\\资料\\gw-资料\\restored_images";

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFilePath), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("File: ")) {
                    String fileName = line.substring("File: ".length());
                    String base64Data = reader.readLine().trim();
                    byte[] imageBytes = Base64.getDecoder().decode(base64Data);

                    Path outputPath = Paths.get(outputFolderPath, fileName);
                    Files.createDirectories(outputPath.getParent());
                    Files.write(outputPath, imageBytes);

                    System.out.println("Image \"" + fileName + "\" restored.");
                }
            }
            reader.close();
            System.out.println("All images have been restored.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值