通过 jdk 自带的编、解码器进行BASE64编码、解码

代码来自 Java 处理图片 base64 编码的相互转换

package org.navis.codec;

import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import org.junit.Test;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * base64编码、解码测试
 * Created by LingeringNight on 2017-11-16.
 */
public class Base64Test {


    @Test
    public void test(){
        FileInputStream fileInputStream = null;
        byte[] data = null;
        try {
            fileInputStream = new FileInputStream(new File("E:\\Temp\\codec\\out.txt"));
            data = new byte[fileInputStream.available()];
            fileInputStream.read(data);
            fileInputStream.close();
            generateBase64Image(new String(data),"E:\\Temp\\codec\\out.jpg");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 将图片转换成base64编码后的字符串
     * @param filepath 图片文件路径
     * @return 编码后字符串
     */
    @Nullable
    public static String getImageString(String filepath){
        InputStream inputStream = null;
        byte[] bytes = null;

        try {
            inputStream = new FileInputStream(new File(filepath));
            int size = inputStream.available();
            bytes = new byte[size];
            inputStream.read(bytes);
            inputStream.close();
        } catch (FileNotFoundException e) {
            System.err.println("Encode Error: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("File IO Error: "+ e.getMessage());
        }

        if(bytes == null){
            return null;
        }
        else{
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(bytes);
        }
    }


    /**
     * 将base64编码转换成图片并保存
     * @param base64string
     * @param filepath
     * @return
     */
    @Contract(value = "null, _ -> false", pure = true)
    public static boolean generateBase64Image(String base64string, String filepath){
        if(base64string == null || base64string.length()<=0){
            return false;
        }
        try {
            File imagineFile = new File(filepath);
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] data = decoder.decodeBuffer(base64string);
            for(int i = 0; i< data.length;++i){
                if(data[i] < 0){
                    data[i]+=256;
                }
            }

            FileOutputStream fileOutputStream = new FileOutputStream(imagineFile);
            fileOutputStream.write(data);
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
           return false;
        }
    }

}

你可能感兴趣的:(JAVA)