Java byte[]数据转base64字符串

直接上代码

package doc.utils.transformation;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 图片数据转换成字符串形式
 */
public class ImageToString {

    /**
     * 将 图片数据 转成 base64 字符串
     * @param imgUrl
     * @return
     */
    public static String byteToString(String imgUrl) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(imgUrl);
        byte[] bytes = new byte[ fileInputStream.available() ];
        fileInputStream.read(bytes);
        fileInputStream.close();
        return new BASE64Encoder().encode(bytes);
    }

    /**
     * 将一个 base64 字符串 转换成一个 字节数组
     * @param base64ImagData
     * @return
     */
    public static byte[] stringToBytes(String base64ImagData) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(base64ImagData);
    }

    /**
     * @param front 拼接后在前面的数组
     * @param after 拼接后在后面的数组
     * @return 拼接后的数组
     * */
    public static byte[] connectBytes(byte[] front, byte[] after){
        byte[] result = new byte[front.length + after.length];
        System.arraycopy(front, 0, result, 0, after.length);
        System.arraycopy(after, 0, result, front.length, after.length);
        return result;
    }

    public static void main(String[] args) {

        try {
            // 图片数据 转成 base64字符串
            String path = "G:\\IMG_1028.JPG";
            String imgBase64 = byteToString(path);

            // base64字符串转 byte[] 数据
            byte[] bytes = stringToBytes(imgBase64);
            
            // 生成图片
            FileOutputStream os = new FileOutputStream("G:\\img\\test.jpg");
            os.write(bytes);
            os.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}

 

posted @ 2019-10-16 20:54  追梦滴小蜗牛  阅读(2880)  评论(0编辑  收藏  举报