Java 图片、文件 Base64 互转

发布时间 2023-08-07 14:48:20作者: VipSoft

Java 图片、文件 Base64 互转

package com.thoth.his.base.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class ImageUtil {

    public void FileToBase64(String filePath) throws IOException {
        FileInputStream inputStream = null;
        try {
            Base64.Encoder encoder = Base64.getEncoder();

            inputStream = new FileInputStream(filePath);

            int available = inputStream.available();
            byte[] bytes = new byte[available];
            inputStream.read(bytes);

            String base64Str = encoder.encodeToString(bytes);
            System.out.println(base64Str);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
        }
    }

    public void Base64ToFile(String base64Str, String saveFilePath) throws IOException {
        FileOutputStream outputStream = null;
        try {
            Base64.Decoder decoder = Base64.getDecoder();

            byte[] bytes = decoder.decode(base64Str);

            outputStream = new FileOutputStream(saveFilePath);

            outputStream.write(bytes);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            outputStream.close();
        }
    }
}