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();
            }
    
    
        }
    
    }
  • 相关阅读:
    Python嵌入C/C++ (Python核心编程)
    c++ 降低文件间类的耦合度及关联度
    Python嵌入C++
    Windows编程学习笔记(十一)
    C++STL算法分析之:非变易算法
    背包九讲
    随机数 srand() & rand()
    C++ explicit 关键字解析
    [抄书]贪心策略的理论基础——拟阵
    WP7之LongListSelector控件
  • 原文地址:https://www.cnblogs.com/oukele/p/11688405.html
Copyright © 2011-2022 走看看