zoukankan      html  css  js  c++  java
  • 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();
            }
    
    
        }
    
    }
  • 相关阅读:
    spring mvc 分页
    get/post时中文乱码问题的解决办法
    mysql-day01
    servler配置
    idea
    springMvc 核心配置
    ServletRequest面试题
    Servlet面试题
    Http面试题
    测试文件
  • 原文地址:https://www.cnblogs.com/oukele/p/11688405.html
Copyright © 2011-2022 走看看